MCP
MCP

Reputation: 4536

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

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.

Upvotes: 3

Views: 4268

Answers (3)

wholerabbit
wholerabbit

Reputation: 11546

"can someone tell me what the "& 0x01" is doing in the printf statement"

That's how you get each digit. The number is shifted down 1, and bitwise ANDed with 1. 1 only has one bit set, the *L*east *S*ignificant one, so AND'ing with that will yield either 1 (if char_to_print also has the LSB set) or zero, if it doesn't.

So, eg, if char_to_print is 4 originally, the first time it's ANDed with 1 yields zero, because the LSB is not set. Then it's shifted down one and AND'ed, another zero. The third time, the LSB is set, so you get 1. Binary 100 is decimal 4.

Upvotes: 3

apmasell
apmasell

Reputation: 7153

There are two problems:

  1. char_to_print >> 1; is doing the bit-shift, but throwing away the result. Try char_to_print = char_to_print >> 1;

  2. You cannot pass a char to printf expecting an integer. You should (int)(char_to_print & 0x01).

Upvotes: 1

stefan bachert
stefan bachert

Reputation: 9606

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++)

Upvotes: 8

Related Questions