cplusplus.com
C++ : Forum : General C++ Programming : Hex bytes to integer
 
cplusplus.com
Information
Documentation
Reference
Articles
Forum
Forum
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programming
Lounge
Jobs


post Hex bytes to integer

Jo3Bingham (5)
I have a byte array and I need to convert the first two bytes to an integer as though they're one byte, but they have to be read backwards.

ie. The first byte is A1 and the second byte is B2. I need to convert them as B2A1.

Thanks ahead of time. :)
jsmith (5804)
If sizeof( unsigned short ) == 2 and your platform is little endian (Intel), then
just

1
2
unsigned char byte_array[ 2 ]; // ...
unsigned short val = *(unsigned short*)byte_array;

helios (9402)
Regardless of platform, you can do unsigned long a=array[0]|(array[1]<<8); and it will always work (unless sizeof(unsigned long)<2).
Last edited on
Jo3Bingham (5)
Thanks helios, you too jsmith.
Topic archived. No new replies allowed.