Search code examples
c++unsignedunsigned-integer

c++ how to store four 8 bit integers as a 32 bit unsigned integer?


I have four integers and I need to convert them into an unsigned 32 bit integer. I am converting an HDR image into LDR output image data.


Solution

  • You have four 8-bit integers, and you want to combine them into one 32-bit integer. The way to do that is to use bit-shifting, eg:

    uint8_t ui1, ui2, ui3, ui4;
    
    // set values to ui1..ui4 as neeed...
    
    uint32_t ui32 = (uint32_t(ui1) << 24) | (uint32_t(ui2) << 16) | (uint32_t(ui3) << 8) | uint32_t(ui4);
    
    // use ui32 as needed...
    

    Or, change the order of ui1..ui4 if you need the endian of ui32 to be reversed:

    uint32_t ui32 = (uint32_t(ui4) << 24) | (uint32_t(ui3) << 16) | (uint32_t(ui2) << 8) | uint32_t(ui1);
    

    UPDATE: Given your comment:

    Would this work if I have expressed the numbers as normal "int" ?

    Yes, this can be applied in that situation too. You just need to add some bit masking to ensure the int values don't exceed 8 bits each, eg:

    int i1, i2, i3, i4;
    
    // set values to i1..i4 as neeed...
    
    uint32_t ui32 = (uint32_t(i1 & 0xFF) << 24) | (uint32_t(i2 & 0xFF) << 16) | (uint32_t(i3 & 0xFF) << 8) | uint32_t(i4 & 0xFF);
    
    // use ui32 as needed...
    

    Be sure the int values are in the range 0..255, inclusive, so that no data loss occurs during the bit masking.