将字节和剩余值转换为 int(对二进制补码感兴趣) [英] Shifting bytes and remaining values casted to int (interested in two's complement)

查看:13
本文介绍了将字节和剩余值转换为 int(对二进制补码感兴趣)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么您在下面看到的代码会给出这些结果?

Why does the code that you see below give these results?

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

平移 y 的 int 为:16640

The int shifted y is: 16640

整数 z 为:194

如果我将测试更改为 00000001,它会表现得很好:

While if I change the test to 00000001 it performs great:

更改的代码:

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 开始检查 返回一个字节,有人说它是有符号的,如果我销毁这些值,则返回一些无符号的字节,因为我必须做一些移位.

My problem is that I have two bytes that I want to read from data registers from an accelerometer. The value is stored in two's complement so I wanted to check since wire.read returns a byte that some people say that is signed and some unsigned if I destroy the values, because I have to do some shifting.

所以我想检查我是否有一个字节,我尝试将它移动并将它存储到一个 int,我得到了什么值,我想测试我是否可以以某种方式将带符号的字节值存储在一个字节数组中.

So I wanted to check if I have a byte and I try to shift it and store it to an int, what values do I get, and I want to test if somehow I can store signed byte values inside a byte array.

推荐答案

上面显示的答案是正确的,因为 Alexy Frunze 说从 0 开始的数字是八进制.

The answer shown above is correct as Alexy Frunze said number starting with 0 is octal .

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

这篇关于将字节和剩余值转换为 int(对二进制补码感兴趣)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆