Shifting bytes and remaining values casted to int

2019-08-31 02:01发布

问题:

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

Results:

The byte test is: 65

The int x is: 65

The int shifted y is: 16640

The int z is: 194

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

Changed code:

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

Results:

The byte test is: 1

The int x is: 1

The int shifted y is: 256

The int z is: 130

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.

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.

回答1:

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


回答2:

Just because you write a number that "looks binary" since it has a lot of 1s and 0s and is 8 digits wide, doesn't make it magically a binary literal. How would you expect:

byte x = 100;

and

byte x = 100;

to know the value is supposed to be 10010 (one hunded or 1002 (four)?

In fact, C (and C++) don't even have binary literals built-in: a numeric literal starting with 0 is interpreted as octal, base 8.