Question

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];
Was it helpful?

Solution

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

OTHER TIPS

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top