-->

转移字节,其余铸造到int类型(感兴趣的二进制补码)(Shifting bytes and rema

2019-10-29 14:02发布

为什么你看到下面的代码给这些结果?

void loop() {
    byte test = 00000101;
    Serial.print("The byte test is: ");
    Serial.println(test);
    int x = (int)test;
    int y = (int)test<<8;
    Serial.print("The int x is: ");
    Serial.println(x);
    Serial.print("The int shifted y is: ");
    Serial.println(y);

    byte tost = 10000001;
    int z = test + tost;
    Serial.print("The int z is: ");
    Serial.println(z);

    delay(1000);
}

结果

字节测试:65

的int x是:65

的int转移y为:16640

的int z是:194

虽然如果我改变了测试,以00000001它执行很大:

改变的代码:

void loop() {
    byte test = 00000001;
    Serial.print("The byte test is: ");
    Serial.println(test);
    int x = (int)test;
    int y = (int)test<<8;
    Serial.print("The int x is: ");
    Serial.println(x);
    Serial.print("The int shifted y is: ");
    Serial.println(y);

    byte tost = 10000001;
    int z = test + tost;
    Serial.print("The int z is: ");
    Serial.println(z);

    delay(1000);
}

结果:

The byte test is: 1

The int x is: 1

The int shifted y is: 256

The int z is: 130

我的问题是,我有我想从数据寄存器从加速度计读取的两个字节。 该值存储在补 ,所以我想检查,因为wire.read如果我破坏值,因为我必须做一些转移返回一个字节,有些人说是有符号和一些未签名。

所以,我想检查,如果我有一个字节,我推诿,并将其存放到一个int,我得做什么价值观,我想测试,如果不知何故,我可以存储一个字节数组内签署字节值。

Answer 1:

上面示出的答案是正确的,因为阿列克西伏龙芝所述从0开始数为八进制。

000000101 is 65 not 5
65 << 8 =16640
10000001 in decimal is 129
129+65 = 194


Answer 2:

仅仅因为你写一个数字,“看起来二进制”,因为它有很多的1和0为8位宽,不会使奇迹般地一个二进制文字。 你会如何期待:

byte x = 100;

byte x = 100;

要知道的值被认为是100 10(一个或hunded 100 2(4)?

事实上,C(和C ++)甚至不用二进制文字内置:数字文字开始0被解释为八进制 ,基座8。



文章来源: Shifting bytes and remaining values casted to int (interested in two's complement)