简体   繁体   中英

Two's complement stm32 c

I have a number that is "significant byte", it may be 0 or 255.

Which means 0 or -1.

How to convert 255 to -1 in one time.

I have a function that doesn't works for me:

acc->x = ((raw_data[1]) << 8) | raw_data[0];

Assuming that every 8th bit set to 1 means negative (254 == -2) then a widening conversion from signed types should do:

int n = (signed char)somebyte;

so

unsigned char rawdate[2] = ...;
int msbyte = (signed char)rawdata[1];
acc->x = (msbyte << 8) | (raw_data[0] & 0xFF);

I am not sure what is required but here are the rules for arithmetic conversions of integers.

If an integer is assigned to another lower bit integer, the data will be truncated.

Example:

struct A {
    int c1 : 8;
    unsigned c2 : 8;
} a;

int main()
{
    short int i = 255;  // right 8 bits containing all bits set
    a.c1 = i;       // or a.c1 = 255. casting not required. 
    a.c2 = i;       // same as above.
    // prints -1, 255
    printf("c1: %d c2: %d\n", a.c1, a.c2);

    i = 511;        // 9 number of 1 bits
    a.c1 = i;       // left 9th bit will be truncated. casting not required.
    a.c2 = i;       // same as above
    // prints -1, 255
    printf("c1: %d c2: %d\n", a.c1, a.c2);

    return 0;
}

If a signed 8 bit integer (or char) is assigned to higher bit integer (say int), it's sign bit will be shifted.

ex:

char c = 255; // which is -1
int i = c; // i is now -1. sign bit will be shifted to 32nd bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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