如果使用了无符号表示和带符号幅度表示,那么32位1011 0010 0101 0000 0000 0000 0000 0000这个字的十进制数是多少?
答案 0 :(得分:0)
要获得负值,需要通过数字反转所有位并添加一个 参见:
#include <stdio.h>
unsigned int Bin2Dec(const char *cs){
unsigned int r=0;
for ( r=0;*cs; ++cs) {
switch (*cs) {
case '0':
break;
case '1':
break;
default:
continue;
}
r = (r << 1) | ( *cs - '0');
}
return r;
}
void PrintBin(unsigned int n) {
int i;
printf("%12d : ",n);
for (i=31; i >=0; --i) {
int b=((1<<i) & n) >> i;
printf(" %u",b);
}
printf("\n");
}
int main() {
unsigned int u= Bin2Dec("1011 0010 0101 0000 0000 0000 0000 0000");
printf("unsigned is %u , signed is %d\n",u, u);
PrintBin(u); // For test
u=~u + 1; // Invert all the bits through the number and add one
printf("%u %d\n",u, u);
PrintBin(u);
return 0;
}
输出:
unsigned是2991587328,签名是-1303379968
-1303379968:1 0 1 1 0 0 1 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1303379968 1303379968
1303379968:0 1 0 0 1 1 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0