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

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: none

To do: Converting the decimal to binary numbers using bitwise operator in C program

To show: How to 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

printf("%7u = ", number);

for(q = 1; q < 16; q++)

{

// combining variable number with variable DisplayMask

// 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 . . .