I think JoBe got it, folks are smart in Belgium!
Just in case there are some stragglers, here is another twist to Dave's wonderful code. I am trying to make the whole thing more visible ...
[php]
// bitwise operations << shift left, >> shift right, & bitwise AND
// a nibble is 4 bits, char is 8 bits, int is 32 bits
// try to store values 3, 7, 14, 6 in an integer
#include
// prototype
void dec2bin(long decimal, char *binary);
int main ()
{
unsigned int x;
unsigned char nibble;
char binary[80];
x = 0;
printf("count groups of 4 bits (nibbles) from right to left ...\n\n");
// put 3 into the first group of 4 bits (nibble #0)
x = 3 << (0 * 4);
dec2bin(x,binary);
// added 00 to make the groups of 4 bits show better
printf("value 3 in nibble #0 = 00%s\n", binary);
// put 7 into the second group of 4 bits (nibble #1)
x += 7 << (1 * 4);
dec2bin(x,binary);
printf("value 7 in nibble #1 = 0%s\n", binary);
// put 14 into the third group of 4 bits (nibble #2)
x += 14 << (2 * 4);
dec2bin(x,binary);
printf("value 14 in nibble #2 = %s\n", binary);
// put 6 into the fourth group of 4 bits (nibble #3 and so on, plenty of space)
x += 6 << (3 * 4);
dec2bin(x,binary);
printf("value 6 in nibble #3 = %s\n", binary);
printf("\n... retrieve values ...\n\n");
// retrieve the values in nibble #0, #1, #2 and #3
// & is bitwise AND, 0xF is binary 1111
nibble = ( x >> (0 * 4) ) & 0xF;
printf ( "value in nibble #0 = %d\n", nibble );
nibble = ( x >> (1 * 4) ) & 0xF;
printf ( "value in nibble #1 = %d\n", nibble );
nibble = ( x >> (2 * 4) ) & 0xF;
printf ( "value in nibble #2 = %d\n", nibble );
nibble = ( x >> (3 * 4) ) & 0xF;
printf ( "value in nibble #3 = %d\n", nibble );
getchar(); // wait
return 0;
}
//
// accepts a decimal integer and returns a binary coded string
//
void dec2bin(long decimal, char *binary)
{
int k = 0, n = 0;
int neg_flag = 0;
int remain;
char temp[80];
do
{
remain = decimal % 2;
decimal = decimal / 2; // whittle down decimal
temp[k++] = remain + 0x30; // makes characters 0 or 1
} while (decimal > 0);
while (k >= 0)
binary[n++] = temp[--k]; // reverse spelling
binary[n-1] = 0; // end with NULL = EOS
}
[/php]