2017-03-16 81 views
-3

我剛剛閱讀這個鏈接http://www.mathcs.emory.edu/~cheung/Courses/255/Syllabus/1-C-intro/bit-array.html 我有一個問題,我做了一個128位數組,因此我使用了一個數組int A [4]。我可以設置位和測試位,但如何將這些位打印出來,例如000001000 .....? 我用一個簡單的代碼來打印在int數組中打印出位

for(int i=0;i<128;i++) 
{ 
cout<<A[i];// i tried cout << static_cast<unsigned int>(A[i]); 
} 

結果是不是我要找的 enter image description here

感謝您的閱讀。

+4

別t垃圾郵件標籤。這不是C.並且不要發佈文字的圖像。提供[mcve]。 – Olaf

+0

如果您聲明瞭4個int元素的數組,則引用索引0 ... 3之外的任何元素將調用* undefined behavior *,這是您的代碼在該循環過程中執行124次的一些操作。 – WhozCraig

+0

@WhozCraig謝謝,那麼你能指導我解決它的一些方法嗎? – Van

回答

1

根據結果測試位並打印0或1。

for(int i=0;i<128;i++) { 
    if((A[i/32]>>(i%32))&1) { 
     cout<<'1'; 
    } else { 
     cout<<'0'; 
    } 
} 

,或者更簡單的:

for(unsigned i=0; i<128; ++i) { 
    cout << ((A[i/32]>>(i%32))&1); 
} 

(這一切都假定A是某種類型的,它至少32位寬的陣列;理想地,這將是uint32_t

1

您正在一對夫婦不幸的假設:

  • int並不總是32位
  • 你有4個int變量,而不是128倍「一位」的數組變量

喜歡的東西是這樣的:

#include <stdio.h> 
#include <stdlib.h> 
#include <stdint.h> /* uint32_t comes from here */ 

void main(void) { 
    int i, j; 
    uint32_t t; 
    uint32_t data[4]; 

    /* populate the data */ 
    for (i = 0; i < 4; i++) { 
     data[i] = rand(); 
    } 

    /* print out the 'bits' for each of the four 32-bit values */ 
    for (i = 0; i < 4; i++) { 

     t = data[i]; 

     /* print out the 'bits' for _this_ 32-bit value */ 
     for (j = 0; j < (sizeof(data[0]) * 8); j++) { 

      if (t & 0x80000000) { 
       printf("1"); 
      } else { 
       printf("0"); 
      } 

      t <<= 1; 
     } 

     printf("\n"); 
    } 
} 

輸出:

01101011100010110100010101100111 
00110010011110110010001111000110 
01100100001111001001100001101001 
01100110001100110100100001110011