atomSmasher atomSmasher - 2 months ago 8
C++ Question

Bitwise AND not calculating the expected value

What am I missing here?

#include <vector>
#include <stdint.h>
#include <iostream>

int main()
{
uint16_t week = 900;
std::vector <uint8_t>out;

out.push_back(0x00ff & week);
out.push_back(0xff00 & week);

for (int i = 0; i < out.size(); i++)
{
std::cout << std::hex << (int)out[i] << std::endl;
}

return 0;
}


expected output

84

03

actual output

84

00

Answer

Bitwise AND is calculating the correct value. There is nothing wrong with the expression 0xff00 & week, it produces the value 0x0300 (with week being 900). The value gets truncated when it's moved into the container, that can only store values of type uint8_t.

To store the upper byte of a uint16_t, you'll have to shift it right:

out.push_back(0x00ff & week);
out.push_back(0x00ff & (week >> 8));