2015-11-13 02:01 AM
Hi guys i am struggling to convert 2 8bit values into 16bit value, please help me
//Global variable
volatile uint8_t data[16];
volatile uint16_t BIG;
main()
{
data[1] = 23;//msb
data[0] = 21; //lsb
BIG = data[0] | (data[1] << 8);
while(1);
}
but in the output i only get lsb.. MSB is not showing up
#stm32-c
2015-11-13 02:12 AM
>(data[1] << 8)
If the data type of
data[]
is only 8 bits in size, what do you think is left if you shift it by 8 bit ?
BIG = data[0] | ((uint16_t)data[1] << 8);
should work.
2015-11-13 03:11 AM
hey Avatar thanks for your time, this is 32 bit MCU the 8 bit data is moved to 32bit general purpose registers R1 or R2 before shifting so there is enough space i guess. Anyway i got the solution is some way BIG = (data[2] << 8 | data[3]);
it works thanks people2015-11-13 04:07 AM
> ... this is 32 bit MCU ...
You are wrong here, in the sense that this does not matter. The behavior you are observed is defined in the C language standard. I would suggest to again read and digest especially the part about automatic type promotions.
2015-11-13 07:30 AM
@AvaTar
Sorry to say, but it's you who is wrong. The value will be implicitly converted to ''unsigned int'' (which is 32-bit on STM32) before shifting. See here forhttps://stackoverflow.com/questions/18370197/does-bit-shift-automatically-promote-chars-to-int
. @jagadeesh.puneeth This code is working for me, and printing 0x1234:int
main() {
volatile
uint8_t data[2];
volatile
uint16_t BIG;
data[0] = 0x12;
//msb
data[1] = 0x34;
//lsb
BIG = data[1] | (data[0] << 8);
printf
(
''BIG = 0x%x
''
, BIG);
while
(1) {
}
}
Also, when constructing integers bigger than one byte be careful not to get the bytes in the wrong order as STM32 is
.
2015-11-13 12:57 PM
Nice :) thanks man i appreciate it.