Iterate through char array, printing bits of each char (in C)

bit-shift, c, char

Solution

You missed that

                   char_to_print >>= 1;

char_to_print was not shifted AND saved

And you should initialize bit each time with an new char_to_print

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

Problem

Trying to print out the bits of each char stored in an array. I've looked up some code and tried a version to suit my needs. Problem is that I only seem to be getting the first char in the array. ``` //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"); } ``` Basically what I'm getting is: `00000000` Not sure why this is. Through debugging I've found it only to be printing the first bit and nothing else. I've also proven that the outer loop is actually iterating through int's 0 - 29... So it should be iterating through the char's in the array. I'm stumped. Also, can someone tell me what the `& 0x01` is doing in the `printf` statement. I found that in someone else's code and I am unsure.

Original source

Related problems