Solution for Exercise 17-11

ex1711

#include <stdio.h>

char *binbin(unsigned n);

int main()
{
    unsigned bshift,x;

    printf("Type a value 0 to 255: ");
    scanf("%u",&bshift);

    for(x=0;x<8;x++)
    {
        printf("%s %d\n",binbin(bshift),bshift);
        bshift <<= 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

Type a value 0 to 255: 12
0000000000001100 12
0000000000011000 24
0000000000110000 48
0000000001100000 96
0000000011000000 192
0000000110000000 384
0000001100000000 768
0000011000000000 1536

Notes

* I used an assignment operator at Line 15: <<=. Any time you see an expression like:

bshift = bshift << 1;

Consider using an assignment operator instead.