2011-12-10 259 views
1

我有一个数字是“有效字节”,它可能是0或者255,它可能是0或者说255.二进制补码stm32 c

这意味着0或-1。

如何一次性将255转换为-1。

我有一个功能,不工作对我来说:

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

回答

2

假设设置为1的每个第8位表示负(254 == -2),然后从扩大转换签署类型应这样做:

int n = (signed char)somebyte; 

所以

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

这似乎对我来说http://pastebin.com/uGaM29b4 – SevenDays

+2

不,它必须是'(符号字符)'因为标准允许'char'是不起作用无论是签名还是未签名。 –

+0

非常感谢你!现在它工作。 – SevenDays

1

我没有确定需要什么,但这里是整数算术转换的规则。

如果将整数分配给另一个较低位整数,则数据将被截断。

实施例:

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

如果有符号的8位整数(或字符)被分配到更高位的整数(比如INT),它的符号位将被转移。

例如:

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

这个问题被标记为C,而不是C++。 –

+0

好的,谢谢你展示我的错误。我会修改答案。 –

+0

谢谢,你的前任。也帮助我。 – SevenDays