It is often safer to use unsigned types to set bits, because shifts with negative values have an implementation-dependent effect. A simple char can be either signed or unsigned (traditionally it is not signed on MacIntosh platforms, but signed on a PC). Therefore, first enter the character in the unsigned char type.
Then your friends are bitwise logical operators ( & , | , ^ and ~ ) and shift operators ( << and >> ). For example, if your character is in the variable x , then to get the 5th bit you simply use: ((x >> 5) & 1) . The shift operators move the value to the right, discarding the five lower bits and moving the bit, you are interested in the "low position" (it is also the "most right"). The bitwise AND with 1 just sets all other bits to 0, so the resulting value is either 0 or 1, which is your bit. Please note that I start from scratch, not from scratch.
If you assume that your characters have 8 bits, you can write your code as:
unsigned char x = (unsigned char)your_character; int i; for (i = 7; i >= 0; i --) { if (i != 7) printf(","); printf("%s", ((x >> i) & 1) ? "true" : "false"); }
You may notice that since I am the number of bits from right to left, but you want to output from left to right, the loop index should decrease.
Please note that according to the C standard, unsigned char has at least eight bits, but may have more (currently only a few built-in DSPs have characters that are not 8-bit). To be more secure, add this next to the beginning of your code (as a top-level declaration):
#include <limits.h> #if CHAR_BIT != 8 #error I need 8-bit bytes! #endif
This will prevent successful compilation if the target system proves to be one of those special built-in DSPs. In the note to the note, the term “byte” in the C standard means “elementary memory block that corresponds to an unsigned char value”, so in C-talk a byte can have more than eight bits (a byte is not always an octet). This is a traditional source of confusion.