Separating 2 byte number into two 1 bytes

I'm trying to break a 2-byte number into two 1 byte numbers. But I get wrong result. Assumed number is: 0x1234H

uint8_t high = 0;
uint8_t low = 0;

high = static_cast<uint8_t >(val & 0xFF);
low = static_cast<uint8_t >(val >> 8);

cout << std::bitset<8>(high) << endl;
cout << std::bitset<8>(low) << endl;

cout << "high byte: " << static_cast<int >(high) << endl;
cout << "low byte: " << static_cast<int >(low) << endl;

When I run the code I expect to get the following output:

0x1234
00001100
00010010
high byte: 12
low byte: 34

Yet instead I get,

0x1234
00110100
00010010
high byte: 34
low byte: 12

Why do I fail in my attempt?

Upvotes: 1

Views: 383

Answers (1)

user180247
user180247

Reputation:

That's because you've named the variables wrong on these lines...

high = static_cast<uint8_t >(val & 0xFF);
low = static_cast<uint8_t >(val >> 8);

The >> operator is shifting bits downward from high bit positions to low bit positions. If you have to shift those bits down to preserve them (in the cast) that's because they weren't originally the low bits. So...

low = static_cast<uint8_t >(val & 0xFF);
high = static_cast<uint8_t >(val >> 8);

BTW - the bitwise and operator is redundant when you're casting to uint8_t anyway - that's already enough to discard all but the low byte. It's still correct, just not necessary.

Upvotes: 3

Related Questions