按位且不计算期望值

Bitwise AND not calculating the expected value

本文关键字:计算 期望值      更新时间:2023-10-16

我在这里错过了什么?

#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

Bitwise AND 计算正确的值。表达式0xff00 & week没有问题,它产生值0x0300(其中week为900)。当该值移动到容器中时,该值将被截断,该容器只能存储uint8_t类型的值。

要存储uint16_t的上字节,必须将其右移:

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