atomSmasher atomSmasher - 1 year ago 75
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



actual output



Answer Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download