Solution for Exercise 17-10

ex1710

#include <stdio.h>

char *binbin(unsigned char n);

int main()
{
    unsigned bshift,x;

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

    for(x=0;x<8;x++)
    {
        printf("%s\n",
                binbin((unsigned char)bshift));
        bshift = bshift << 1;
    }
    return(0);
}

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

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

Output

Type a value from 0 to 255: 1
00000001
00000010
00000100
00001000
00010000
00100000
01000000
10000000

Notes

* Above, You can see the 1 bit march left across each position in the byte. This output shows the shift in action.