eyesima
eyesima

Reputation: 235

How convert an unsigned int to two unsigned shorts in C++?

I originally had 2 WORD (that's 4 bytes). I have stored them in an unsigned int. How can I split this such that I have 2 (left-most) bytes in one unsigned short variable and the other 2 bytes in another unsigned short variable?

I hope my question is clear, otherwise please tell me and I will add more details! :)

Example: I have this hexadecimal stored in unsigned int: 4f07aabb

How can I turn this into two unsigned shorts so one of them holds 4f07 and the other holds aabb?

Upvotes: 1

Views: 1310

Answers (1)

flyx
flyx

Reputation: 39778

If you are sure that unsigned int has at least 4 bytes on your target system (this is not guaranteed!), you can do:

unsigned short one = static_cast<unsigned short>(original >> (2 * 8));
unsigned short two = static_cast<unsigned short>(original % (1 << (2 * 8)));

This is only guaranteed to work if the original value indeed only contains a 4-byte value (possibly with padding zeroes in front). If you're not fond of bitshifting, you could also do

uint32_t original = 0x4f07aabb; // guarantee 32 bits
uint16_t parts[2];
std::memcpy(&parts[0], &original, sizeof(uint32_t));
unsigned short one = static_cast<unsigned short>(parts[0]);
unsigned short two = static_cast<unsigned short>(parts[1]);

This will yield the two values depending on the target system's endianness; on a litte-endian architecture, the results are reversed. You can check endianness with upcoming C++20's std::endian::native.

Upvotes: 5

Related Questions