Wednesday, 6 February 2019

Convert a Decimal Number to Binary, Octal, Hexadecimal using bitwise operator

In this post, I will show you a generalized way to convert a decimal number (Base 10) to Binary (Base 2), Octal (Base 8), Hexadecimal (Base 16).

First, Let us see how will we convert a decimal number to binary.
I will write a function in C which will accept a decimal number in the parameter and return an array of binary numbers.

int* getBinaryNumber(int number)
{
static int binaryNumberArray[32];
int i;
for(i=31;i>=0;i--)
{
binaryNumberArray[i]= number & 1;
number = number >> 1;
}
return binaryNumberArray;
}

Suppose we send a decimal number 12 to the function.

So,

Iteration 1:
binary[31] = 12 & 1 = 0 [Internally: 1100 & 0001 = 0000 ]
number = number >> 1 [Internally 1100 >> 1 = 0110 ]

Iteration 2:
binary[30] = 6 & 1 = 0 [Internally: 0110 & 0001 = 0000 ]
number = number >> 1 [Internally 0110 >> 1 = 0011 ]

Iteration 3:
binary[29] = 3 & 1 = 1 [Internally: 0011 & 0001 = 0001 ]
number = number >> 1 [Internally 0011 >> 1 = 0001 ]

Iteration 4:
binary[30] = 1 & 1 = 1 [Internally: 0001 & 0001 = 0001 ]
number = number >> 1 [Internally 0001 >> 1 = 0000 ]

So the final Output is 1100 [ bottom to top ]

It has been observed that we have to perform the bit-wise & operation with the number which is 1 less than the base we want to convert (2-1 = 1 in case of binary, 8-1 = 7 in case of octal and so on)

It is also observed that we have to right-shift the bits which is equal to the power of 2 raised to get the value of the base.
For binary it is 2^1 = 2  so we right-shift by 1 bit.
For octal it is 2^3 = 8 so we right-shift by 3 bits.
For Hex it is 2^4 = 16 so we right-shift by 4 bits.

Here is a generalized method to convert a decimal number to binary, octal, hex.
This method will accept a decimal number and the base to which it has to be converted.
2 for Binary
8 for Octal
16 for Hexadecimal

This will return an integer array containing the required converted values.

int* getConvertedNumber(int number,int base)
{
static int converted[32];
int i;

float pow=log(base)/log(2);
int power=(int)pow;
for(i=31;i>=0;i--)
{
converted[i]= n & (base-1);
number= number >> power;
}
return converted;
}

For Hexadecimal, it will have 10 , 11, 12, 13, 14, 15 for A, B, C, D, E, F respectively. 
I have implemented a simple switch case to convert these numbers to its specified letters.

switch(converted[i])
{
case 10:
printf("A");
break;
case 11:
printf("B");
break;
case 12:
printf("C");
break;
case 13:
printf("D");
break;
case 14:
printf("E");
break;
case 15:
printf("F");
break;
default:
printf("%d",converted[i]);
}

By, Abhisek Karmakar
Idea Courtesy, Bratati Das

Convert a Decimal Number to Binary, Octal, Hexadecimal using bitwise operator

In this post, I will show you a generalized way to convert a decimal number (Base 10) to Binary (Base 2), Octal (Base 8), Hexadecimal (Base...