View Single Post
Old 12-03-2006, 11:07 AM   #7 (permalink)
oberon
Quadrature Amplitude Modulator
 
oberon's Avatar
 
Location: Denver
My guess is he wants to print out the binary form of each character. Normally, you could print that using a printf format, but the C standard doesn't require such a format conversion. Here's how to do it.

b.c:
Code:
#include <stdio.h>
void
print_string_in_binary(const char *str)
{
    int i;

    while (*str)
    {
        printf("%d-", *str);
        for (i = 6;i >= 0;i--)
        {
            printf("%d", *str >> i & 0x1);
        }
        printf(" ");
        str++;
    }
    printf("\n");
}
int
main(void)
{
    const char *s = "hello world\n";

    printf("s = %s\n", s);
    print_string_in_binary(s);
    return 0;
}
The key is to print out each bit of a character by shifting it to the least significant bit and bitwise ANDing the resulting integer with 1, which is the maximum binary value. That's what this does: "*str >> i & 0x1". Those of you not well versed with pointers should try to think of *str as str[i] with i being incremented whenever you increment str (note the "i" used here has no relation to the "i" in the print_string_in_binary function).

Result:
Code:
puck% gcc -Wall -o b b.c && ./b
s = hello world

104-1101000 101-1100101 108-1101100 108-1101100 111-1101111 32-0100000 119-1110111 111-1101111 114-1110010 108-1101100 100-1100100 10-0001010
A quick check indicates that this is the correct output.
__________________
"There are finer fish in the sea than have ever been caught." -- Irish proverb

Last edited by oberon; 12-03-2006 at 11:28 AM.. Reason: tweak wording a bit
oberon is offline  
 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76