试图打印出存储在数组中的每个char的位.我查了一些代码并尝试了一个版本以满足我的需求.问题是我似乎只是获取数组中的第一个char.
//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");
}
Run Code Online (Sandbox Code Playgroud)
基本上我得到的是:00000000 不知道为什么会这样.通过调试我发现它只是打印第一位而没有别的.我还证明了外部循环实际上是通过int的0 - 29迭代...所以它应该遍历数组中的char.我很难过.
此外,有人可以告诉我& 0x01在printf声明中做了什么.我发现在其他人的代码中,我不确定.
你错过了
char_to_print >>= 1;
Run Code Online (Sandbox Code Playgroud)
char_to_print未被移位并保存
并且您应该每次使用新的char_to_print初始化位
for (bit = 0; bit < 8; bit++)
Run Code Online (Sandbox Code Playgroud)