Lectures‎ > ‎

Week02

RPi Setup: http://rpi.cs.usfca.edu/

C Programming


Bitwise operators

print_char_bits() challenge

Write a function called print_char_bits(char c) that takes an integer argument and prints the binary representation of the 8 bit character value.

 

For example,

 

print_char_bits('a');

 

Will print:

 

01100001

 

Note this is 0x61 and 97 (base 10).

 

In order to implement print_char_bits() you should use C bitwise operators.

 

You can extra an individual bit value using the & operator.

 

For example, take the char value c.

 

To get the value of least significant bit (the bit at position 0) you can use:

 

int b0;

 

b0 = c & 0b1;

 

To get the value of the second bit (the bit at position 1) you can use:

 

int b1;

 

b1 = (c >> 1) & 0b1;

 

Note the >> operator means "right shift" it will shift all the bit values over by one. So, the bit value in the second position now moves to the first position. With the second bit in the first position, we can use the & operator to extract it's value. You can continue in this way, by shifting each bit into the first position to find it's value with &.

 

Note if you extract the bit values in this way you will want to put them into an array so that you can print the bits in the correct order.


Comments