Parsing a 64bit number into 16bit parts, doesn't work intuitively [solved]

1

I have a string, consisting of 8 chars.

std::string input = { 'A', 'B', 'C', 'D', 'E', 'F', 'A', 'F' };

I have a 64 bit integer which will hold the hexadecimal correspondence of this string. And four 16 bit integers, which the number will be parsed into.

uint64_t number = 0;

uint16_t part0;
uint16_t part1;
uint16_t part2;
uint16_t part3;

I am converting string into a number using stringstream ( never used before )

std::stringstream ss;
ss << std::hex << input;
ss >> number;

I then AND the number with 0x000000FF, and right shift 16 bits.

part0 = number & 0x000000FF;  //output: AF
number >>= 16;

part1 = number & 0x000000FF;  //output: CD
number >>= 16;

part2 = number & 0x000000FF;  //output: 0
number >>= 16;

part3 = number & 0x000000FF;  //output: 0

However, even though string consists of 8 chars, the number is 64 bits, and parts are 16 bits, this just doesn't work when shifting 16 bits. Results are as I noted as comments. It obviously shifting twice as much than it should, so I tried shifting 8 bits, and it works as it supposed to. I am quite baffled, can someone explain why?


edit:

As john pointed out in comments, one hexadecimal digit is 4 bits, not 8, as I thought. This was the problem.

c++
bit-manipulation
asked on Stack Overflow May 3, 2020 by melonduofromage • edited Jun 20, 2020 by Community

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0