Lectures‎ > ‎


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

C Programming

Two challenges: str_to_int() and char_to_binstr()

Bitwise operators

Converting a String to an Integer

Consider the problem of implementing the standard C function atoi(), which takes a string and converts it into an int value.

int str_to_int(char *s);

For example:

char *s = "1234";
int x;

x = str_to_int(s);

printf("x = %d\n", x);

Recall how we can decompose an integer value:

(d3)*(10^3) + (d2)*(10^2) + (d1)*(10^1) + (d0)*(10^0)

Using this knowledge, consider how to write str_to_int using a loop that traverses the input string one character at a time, converts each character code to an integer value, and combines the individual values to construct the complete int value. Note that to get the int value of an ASCII character code, you just need to do this:

char c = '3';
int v;

v = c - '0';

Converting a Character into a Binary String

No consider another problem. We want to write a function that produces a binary string representation of a char value:

void char_to_binstr(char c, char *s);

For example:

char c = 'a';
char s[32];

char_to_binstr(c, s);

printf("s = %s\n", s);

Will print:



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

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

You can extract 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.