如何| 操作员工作?

BO.*_*.LI 0 c++ bit-manipulation

我对|感到困惑 C++中的运算符.我有代码来传输从MCU读取的数据.高8位与低8位分开.并且数据(代码中的BUF)存储补号.所以我用它(BUF[1] << 8) | BUF[0]来获取我的原始数据.但是,结果有点奇怪.例如,现在代码得到d1=-84.如图所示,为什么|操作员不能得到我想要的结果? 在此输入图像描述

#include <cstdlib>
#include <cstdio>
#include <cmath>
#include<iostream>

int main() {
    signed char BUF[2];
    BUF[0] = -84;
    BUF[1] = -2;
    short d1;
    d1 = (BUF[1] << 8) | BUF[0];  // | operator
    std::cout << d1 << std::endl;
    std::cin.get();
}
Run Code Online (Sandbox Code Playgroud)

Lun*_*din 5

你不能左移负数,这样做会调用未定义的行为:任何事情都可能发生.类似地,右移负数也是一个坏主意,因为这可能导致算术或逻辑右移.

您必须将变量转换为无符号类型,shift,然后转换回来.例如:

d1 = ((uint32_t)BUF[1] << 8) ...
Run Code Online (Sandbox Code Playgroud)