/* shift2.c
* Inputs:
* – direction: shift left (0) or right (else)
* – number: shift amount (number of bits)
*/
#include
#include
void print_binary(unsigned char number, int size)
{
if (!number)
{
putc(‘0’, stdout);
return;
}
if (size == 1)
{
putc((number & 1) ? ‘1’ : ‘0’, stdout);
return;
}
print_binary(number >> 1, size – 1);
putc((number & 1) ? ‘1’ : ‘0’, stdout);
}
int main(int argc, char *argv[])
{
unsigned char dir, num, pos;
// Want two arguments, but executable name is always argv[0]
if (argc != 4)
{
printf(“Usage: ./shift2
printf(” direction: shift left (0) or right (1)\n”);
printf(” number: shift amount (number of bits)\n”);
return 1;
}
// atoi() converts strings to integers
dir = atoi(argv[1]);
num = (int)strtol(argv[2], NULL, 16);
pos = atoi(argv[3]);
if (dir) // shift right
{
print_binary(num, sizeof(num) * 8);
printf(” >> %d = “, pos);
print_binary(num >> pos, sizeof(num) * 8);
printf(“\n”);
// printf(“%x >> %x = %x\n”, num, pos, num >> pos);
}
else
{ // shift left
print_binary(num, sizeof(num) * 8);
printf(” << %d = ", pos);
print_binary(num << pos, sizeof(num) * 8);
printf("\n");
// printf("%x << %x = %x\n", num, pos, num << pos);
}
return 0;
}