combine 4 bytes into a 32 bit number - Programmers Heaven

#### Howdy, Stranger!

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

#### Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

# combine 4 bytes into a 32 bit number

Posts: 2Member
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

• Posts: 5Member
Should work . . .

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

[code]
#include

int
main(
void)
{
// 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;
}
[/code]

output is:

0x5678ABC

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

this may not work because you are using signed char.

change it to unsigned char..