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?
As john pointed out in comments, one hexadecimal digit is 4 bits, not 8, as I thought. This was the problem.
User contributions licensed under CC BY-SA 3.0