Skip to main content
puneethj
Associate III
November 13, 2015
Question

Simple integer conversion error

  • November 13, 2015
  • 5 replies
  • 1605 views
Posted on November 13, 2015 at 11:01

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
    This topic has been closed for replies.

    5 replies

    AvaTar
    Senior III
    November 13, 2015
    Posted on November 13, 2015 at 11:12

    >(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.
    puneethj
    puneethjAuthor
    Associate III
    November 13, 2015
    Posted on November 13, 2015 at 12:11

    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 people

    AvaTar
    Senior III
    November 13, 2015
    Posted on November 13, 2015 at 13:07

    > ... 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.

    qwer.asdf
    Senior
    November 13, 2015
    Posted on November 13, 2015 at 16:30

    @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 for

    https://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

    https://en.wikipedia.org/wiki/Endianness

    .
    puneethj
    puneethjAuthor
    Associate III
    November 13, 2015
    Posted on November 13, 2015 at 21:57

    Nice :) thanks man i appreciate it.