简体   繁体   English

如何 操作员工作?

[英]How does the | operator work?

I am feeling confused with the | 我对|感到困惑 operator in C++. C ++中的运算符。 I have code to transfer the data which read from a MCU. 我有代码来传输从MCU读取的数据。 The high 8 bits are seperated from low 8 bits. 高8位与低8位分开。 And the data(the BUF in code) store the complement number. 并且数据(代码中的BUF)存储补码。 So I use (BUF[1] << 8) | BUF[0] 所以我用(BUF[1] << 8) | BUF[0] (BUF[1] << 8) | BUF[0] to get my raw data. (BUF[1] << 8) | BUF[0]获取我的原始数据。 However, the result is a bit strange. 但是,结果有点奇怪。 For example, the now code get d1=-84 . 例如,现在的代码为d1=-84 As the pic shows, why doesn't the | 如图所示,为什么| operator get results as I want? 运算符是否可以根据需要获得结果? 在此处输入图片说明

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

You cannot left-shift negative numbers, doing so invokes undefined behavior: anything can happen. 您不能左移负数,这样做会引起未定义的行为:任何事情都会发生。 Similarly, right-shifting negative numbers is also a bad idea, since that can result in either arithmetic or logical right shift. 同样,右移负数也是一个坏主意,因为这可能导致算术或逻辑右移。

You have to cast the variable to unsigned type, shift, then convert back. 您必须将变量转换为无符号类型,进行移位,然后再转换回去。 For example: 例如:

d1 = ((uint32_t)BUF[1] << 8) ...

The behaviour on left shifting a negative number is undefined , and prior to C++14 you are vulnerable to different complementing schemes for a signed char . 左移负数的行为是不确定的 ,并且在C ++ 14之前,您容易受到带signed char不同补码方案的攻击。 (From C++14 signed char and char if it's signed must be 2's complement.) (从C ++ 14 signed charchar ,如果它的signed必须是2的补数。)

For an easy life, write merely 为了生活轻松,只写

BUF[1] * 256 + BUF[0]

noting that the type of this expression is an int . 请注意,此表达式的类型int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM