Write program to divide integer by 2 using shift operator
The >> shift operator shifts value to the right.
Any bit that's marched off the right end is discarded, and only zero bits are inserted on the left side.
Here's the format:
v = int >> count;
int is an integer value, and count is the number of places to shift the bits to the right.
The result is stored in variable v.
The >> is guaranteed to always cut the value in half when you shift one digit to the right.
#include <stdio.h> char *to_binary(int n); int main()// w ww .j a v a2 s.c o m { int bshift,x; printf("Type a value from 0 to 255: "); scanf("%d",&bshift); for(x=0;x<8;x++) { printf("%s %d\n",to_binary(bshift),bshift); bshift = bshift >> 1; } return(0); } char *to_binary(int 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); }