【问题标题】:Iterate through char array, printing bits of each char (in C)遍历 char 数组,打印每个 char 的位(在 C 中)
【发布时间】:2012-04-28 19:08:34
【问题描述】:

试图打印出存储在数组中的每个字符的位。我查找了一些代码并尝试了一个适合我需要的版本。问题是我似乎只得到了数组中的第一个字符。

//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。我难住了。

另外,谁能告诉我&amp; 0x01printf 语句中做了什么。我在别人的代码中发现了这一点,我不确定。

【问题讨论】:

标签: c char bit-shift


【解决方案1】:

你错过了

                   char_to_print >>= 1;

char_to_print 未移动和保存

你应该每次都用一个新的 char_to_print 初始化 bit

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

【讨论】:

  • 很棒的第二双眼睛,谢谢。我通常在 C++ 中初始化循环中的所有内容,但使用 C 我一直在尝试不同的东西并且没有考虑效果。谢谢。
  • @MCP 您的代码中还有另一个错误:每个 8 位组都以相反的顺序打印。例如,应该是“01010101”的内容被打印为“10101010”。
【解决方案2】:

"谁能告诉我"& 0x01"在printf中做了什么 声明”

这就是你得到每个数字的方式。数字向下移动 1,并与 1 进行按位与运算。1 仅设置一个位,即 *L*east *S* 重要的一个,因此与它进行与运算将产生 1(如果 char_to_print 也具有 LSB设置)或零,如果没有。

因此,例如,如果 char_to_print 最初为 4,则第一次与 1 进行与运算会产生零,因为未设置 LSB。然后它向下移动一个并与,另一个零。第三次设置了 LSB,所以你得到 1。二进制 100 是十进制 4。

【讨论】:

  • 啊,我没有捕捉到那里发生的按位运算。我认为十六进制数字让我有点失望,但现在它完全有道理。感谢您的澄清。
【解决方案3】:

有两个问题:

  1. char_to_print &gt;&gt; 1; 正在执行位移,但丢弃了结果。试试char_to_print = char_to_print &gt;&gt; 1;

  2. 您不能将 char 传递给 printf 并期望整数。你应该(int)(char_to_print &amp; 0x01)

【讨论】:

    猜你喜欢
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 2019-07-30
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多