c - Converting bytes array to integer -
i have 4-byte array (data) of type uint8_t
, represents speed data integer. i'm trying cast array uint32_t
integer (speed), multiply speed 10 , restore 4-byte array (data). data format clear in code below. error:
"assignment expression array type"
the code:
volatile uint8_t data[4] = {0x00 , 0x00, 0x00, 0x00}; volatile uint32_t speed; speed=( uint32_t)*data; speed=speed*10; data=(uint8_t*)speed;
your code doesn't work because during data=(uint8_t*)speed;
don't "lvalue" data, array type can't used in assignment or form of arithmetic. similarly, speed=( uint32_t)*data;
bug because gives first item in array.
the correct way should this:
volatile uint8_t data[4] = {0x00 , 0x00, 0x00, 0x00}; volatile uint32_t speed; speed = (uint32_t)data[0] << 24 | (uint32_t)data[1] << 16 | (uint32_t)data[2] << 8 | (uint32_t)data[3] << 0; speed=speed*10; data[0] = (uint8_t) ((speed >> 24) & 0xffu); data[1] = (uint8_t) ((speed >> 16) & 0xffu); data[2] = (uint8_t) ((speed >> 8) & 0xffu); data[3] = (uint8_t) ((speed >> 0) & 0xffu);
this 100% portable , well-defined code. no implicit promotions take place. code not rely on endianess or other implementation-defined behavior. why write code does, when can write code doesn't?
Comments
Post a Comment