Solution for Exercise 17-14

ex1714

#include <stdio.h>

char *binbin(unsigned n);

int main()
{
    unsigned b,x;

    b = 0x11;

    for(x=0;x<8;x++)
    {
        printf("%s 0x%04X %4d\n",binbin(b),b,b);
        b<<=1;
    }

    return(0);
}

char *binbin(unsigned n)
{
    static char bin[17];
    int x;

    for(x=0;x<16;x++)
    {
        bin[x] = n & 0x8000 ? '1' : '0';
        n <<= 1;
    }
    bin[x] = '\0';
    return(bin);
}

Output

0000000000010001 0x0011 17
0000000000100010 0x0022 34
0000000001000100 0x0044 68
0000000010001000 0x0088 136
0000000100010000 0x0110 272
0000001000100000 0x0220 544
0000010001000000 0x0440 1088
0000100010000000 0x0880 2176

Notes

* The value 0x11 is chosen because it represents an interesting binary pattern, as shown in the output above.