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

Header file: Standard

Additional library: none/default

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

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

 

 

C and C++ Programming Resources | C & C++ Code Example Index