Skip to content

Instantly share code, notes, and snippets.

@JohnAZoidberg
Last active July 2, 2017 07:23
Show Gist options
  • Save JohnAZoidberg/46bf1c3cd3d337db68363ea11006d50f to your computer and use it in GitHub Desktop.
Save JohnAZoidberg/46bf1c3cd3d337db68363ea11006d50f to your computer and use it in GitHub Desktop.
Demonstrate the behaviour of bitshifting in C
#include <stdio.h>
/*** Output looks like the following ***/
/* ******** Signed ********: */
/* Bitshift right (>>=1) */
/* -128 in binary: 10000000 */
/* -64 in binary: xxxxxxxx */
/* */
/* Bitshift right (>>=1) */
/* 64 in binary: 01000000 */
/* 32 in binary: xxxxxxxx */
/* */
/* Bitshift left (<<=1) */
/* 1 in binary: 00000001 */
/* 2 in binary: xxxxxxxx */
/* */
/* */
/* ******* Unsigned *******: */
/* Bitshift right (>>=1) */
/* 128 in binary: 10000000 */
/* 64 in binary: xxxxxxxx */
/* */
/* Bitshift right (>>=1) */
/* 64 in binary: 01000000 */
/* 32 in binary: xxxxxxxx */
/* */
/* Bitshift left (<<=1) */
/* 1 in binary: 00000001 */
/* 2 in binary: xxxxxxxx */
void convert_to_binary(char number) {
unsigned char bit, mask = 128; /* 10000000 in binary */
do {
bit = (number & mask) / mask;
printf("%d", bit);
} while(mask >>= 1);
printf("\n");
}
int main() {
{
printf("******** Signed ********:\n");
char c = -128; /* 10000000 in binary */
printf("Bitshift right (>>=1)\n");
printf("%4d in binary: ", c);
convert_to_binary(c);
c >>= 1;
printf("%4d in binary: ", c);
convert_to_binary(c);
c = 64; /* 01000000 in binary */
printf("\n");
printf("Bitshift right (>>=1)\n");
printf("%4d in binary: ", c);
convert_to_binary(c);
c >>= 1;
printf("%4d in binary: ", c);
convert_to_binary(c);
c = 1; /* 00000001 in binary */
printf("\n");
printf("Bitshift left (<<=1)\n");
printf("%4d in binary: ", c);
convert_to_binary(c);
c <<= 1;
printf("%4d in binary: ", c);
convert_to_binary(c);
}
printf("\n");
/* unsigned */
{
printf("\n******* Unsigned *******:\n");
unsigned char c = -128; /* 10000000 in binary */
printf("Bitshift right (>>=1)\n");
printf("%4d in binary: ", c);
convert_to_binary(c);
c >>= 1;
printf("%4d in binary: ", c);
convert_to_binary(c);
c = 64; /* 01000000 in binary */
printf("\n");
printf("Bitshift right (>>=1)\n");
printf("%4d in binary: ", c);
convert_to_binary(c);
c >>= 1;
printf("%4d in binary: ", c);
convert_to_binary(c);
printf("\n");
printf("Bitshift left (<<=1)\n");
c = 1; /* 00000001 in binary */
printf("%4d in binary: ", c);
convert_to_binary(c);
c <<= 1;
printf("%4d in binary: ", c);
convert_to_binary(c);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment