2016-03-06 61 views

回答

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

輸出:

無符號是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: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 0

相關問題