combine 4 bytes into a 32 bit number

I have 4 numbers:b1 b2 b3 b4 (b1 is MSB, b4 is LSB) and I want to combine them into one number of 32-bit as b1b2b3b4;tried the following but didn't work (i guess overflow):

res = (unsigned long)((b4 & 0xFF) | (((unsigned long)(b3<<8)) & 0xFF00));
res = (unsigned long)(res | (((unsigned long)(b2<<16)) & 0xFF0000));
res = (unsigned long)(res |(((unsigned long)(b1<<24)) & 0xFF000000));

b1 = 86; b2 = 120; b3 = 154; b4 = 188;
result should be : 1450744508 in decimal or 56789abc in hex


  • Should work . . .

    I used your code and wrote it in the following way both gave correct outputs for me.


    // 8-bit values
    char a = 0x56;
    char b = 0x78;
    char c = 0x9A;
    char d = 0xBC;

    // combine into a single 32-bit value
    unsigned int value = d | (c<<8) | (b<<16) | (a<<24);
    std::cout << std::hex << value << std::endl;

    output is:


    Compiled in both x64 and x86, result is the same.
    What output are you getting?
  • Hi.

    this may not work because you are using signed char.

    change it to unsigned char..

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!