按位与不计算期望值

Bitwise AND not calculating the expected value

我在这里错过了什么?

#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;
}

预期输出

84
03

实际产量

84
00

按位与计算出正确的值。表达式 0xff00 & week 没有任何问题,它产生值 0x0300week 为 900)。该值在移入容器时会被截断,该容器只能存储 uint8_t.

类型的值

要存储 uint16_t 的高位字节,您必须将其右移:

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