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
Comments
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?
this may not work because you are using signed char.
change it to unsigned char..