2012-04-28 21 views
2

嘗試打印出存儲在數組中的每個字符的位。我查了一些代碼並嘗試了一個版本以適應我的需要。問題是我似乎只是獲取數組中的第一個字符。通過字符數組進行迭代,打印每個字符的位(在C中)

//read_buffer is the array I want to iterate through, bytes_to_read is the number of 
//index positions I want to_read. (array is statically allocated and filled using read() 
//funct, therefore there are some garbage bits after the char's I want), bytes_to_read 
//is what's returned from read() and how many bytes were actually read into array 
void PrintBits(char read_buffer[], int bytes_to_read) 
{ 

     int bit = 0; 
     int i = 0; 
     char char_to_print; 

     printf("bytes to read: %d\n", bytes_to_read); //DEBUG 

     for (; i < bytes_to_read; i++) 
     { 
       char_to_print = read_buffer[i]; 

       for (; bit < 8; bit++) 
       { 
         printf("%i", char_to_print & 0X01); 
         char_to_print >> 1; 
       } 
       printf(" "); 
       printf("bytes_to_read: %d -- i: %d", bytes_to_read, i); 
     } 

     printf("\n"); 
} 

基本上我得到的是:00000000不知道這是爲什麼。通過調試,我發現它只是打印第一位,沒有別的。我也證明了外層循環實際上是通過int的0 - 29迭代的...所以它應該遍歷數組中的char。我很難過。
*另外,有人可以告訴我什麼「& 0x01」正在做的printf語句。我發現在別人的代碼中,我不確定。大聲笑...也許這是我的問題?

回答

7

你錯過了

    char_to_print >>= 1; 

char_to_print沒有轉移並保存

你應該每次初始化位與新char_to_print

  for (bit = 0; bit < 8; bit++) 
+0

真棒第二套眼睛,謝謝。我通常在C++中初始化我的循環中的所有內容,但使用C我一直在嘗試不同的東西,並沒有考慮到這些效果。謝謝。 – MCP 2012-04-28 19:19:48

1

有兩個問題:

  1. char_to_print >> 1;正在做位移,但扔掉結果。嘗試char_to_print = char_to_print >> 1;

  2. 您無法將char指定爲期望整數的printf。你應該(int)(char_to_print & 0x01)

3

「有人可以告訴我是什麼」 & 0×01"

這就是你如何讓每一位在printf的 聲明做」。該數字向下移位1,並且與1進行按位與運算。1只有一個位設置,* L * east * S *顯着位,因此AND與這將產生1(如果char_to_print也有LSB設置)或零,如果它不。

因此,例如,如果char_to_print最初是4,則第一次與1進行AND操作時會得到零,因爲LSB未設置。然後它向下移動一個AND'ed,另一個零。第三次,LSB設置,所以你得到1.二進制100是十進制4.

+0

啊,我沒有發現那裏發生的按位操作。我認爲這個十六進制數字讓我有點感動,但現在它完全有道理。謝謝你的澄清。 – MCP 2012-04-28 19:47:24