Tuesday, 17 March 2015

convert the decimal to binary numbers using bitwise operator in C programming

// bitwise operators
#include <stdio.h>

// function prototype
void DisplayBits(unsigned);

int main(void)
{
unsigned p;

// prompt user for input
printf("Enter an unsigned integer: ");

// read and store the data
// scanf("%u", &p);
scanf_s("%u", &p, 1);

// function call
DisplayBits(p);

return 0;
}

// function definition
void DisplayBits(unsigned number)
{
unsigned q;

// 2 byte, 16 bits position operated bit by bit and hide/mask other bits
// using left shift operator, start with 10000000 00000000
unsigned DisplayMask = 1<<15;
printf("%7u = ", number);

for(q = 1; q < 16; q++)
{
// combining variable number with variable DisplayMask
putchar(number & DisplayMask ? '1':'0');
// number variable is left shifted one bit
number<<= 1;
// separate by 8 bits position (1 byte)
if(q % 8 == 0)
putchar(' ');
}
putchar('\n');
}


Output example:

Enter an unsigned integer: 200
200 = 00000000 1100100
Press any key to continue . . .

No comments:

Post a Comment