Skip to content

Instantly share code, notes, and snippets.

@dbc2201
Created November 24, 2018 18:09
Show Gist options
  • Save dbc2201/986ae470adfc0277a55777a45e00855c to your computer and use it in GitHub Desktop.
Save dbc2201/986ae470adfc0277a55777a45e00855c to your computer and use it in GitHub Desktop.
How to do bit-wise shifting in C
#include <stdio.h>
void dec_to_bin(int n);
int main()
{
int x = 4;
dec_to_bin(x);
printf("\n4 << 1\t");
dec_to_bin(x << 1);
printf("\n4 >> 1\t");
dec_to_bin(x >> 1);
printf("\n4 << 2\t");
dec_to_bin(x << 2);
printf("\n4 >> 2\t");
dec_to_bin(x >> 2);
return 0;
}
void dec_to_bin(int n)
{
char arr1[80];
char digits[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'C', 'D', 'E', 'F'};
int i, j, imax, temp, base, remainder;
long quotient = (long) n;
long number;
number = quotient;
base = 2;
for ( i = 0 ; quotient > 0 ; i++ )
{
remainder = quotient % base;
quotient /= base;
arr1[i] = digits[remainder];
}
imax = i;
for ( i = 0, j = imax - 1; i < imax / 2 ; i++, j-- )
{
temp = arr1[i];
arr1[i] = arr1[j];
arr1[j] = temp;
}
printf("%d = (", number);
for ( i = 0 ; i < imax ; i++ )
{
printf("%c ", arr1[i]);
}
printf("\b)%d", base);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment