計算機編碼--c語言中輸出float的十六進制和二進制編碼


  c語言中沒有可以直接打印float類型數據的二進制或者十六進制編碼的輸出格式,

因此,需要單獨給個函數,如下:

 1 unsigned int float2hexRepr(float* a){
 2     unsigned int c;  
 3     c= ((unsigned int*)a)[0];  4     return c;
 5 }
 6 
 7 int main(int argc, char const *argv[])
 8 {
 9     printf("%s\n", "== in float representation == ");
10     float f1 = 15213.0;
11     printf("%x\n", float2hexRepr(&f1));
12 }

結果如下:

1 == in float representation ==
2 466db400

為了更好看,打印出二進制:

 1 void hex2binaryStr(unsigned int x, char* str){
 2     unsigned int xCopy = x;
 3     for (int i = 0; i < 32; ++i)
 4     {
 5         str[31 - i] = (xCopy & 1)? '1': '0';
 6         xCopy = xCopy >> 1;
 7     }
 8 }
 9 
10 void printBinary(char* str){
11     for (int i = 0; i < 32; ++i)
12     {
13         printf("%c", str[i]);
14         if (((1+i)%4 == 0) && ((1+i) != 32))
15         {
16             printf("%c", ',');
17         }
18     }
19     printf("\n");
20 }

結果如下:

1 == in float representation ==
2 466db400
3 0100,0110,0110,1101,1011,0100,0000,0000

 

THE END

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM