Number System - Covert a Decimal Number to Octal and Hex Number

Oct 23, 2015

It is  very interesting topic. If we simple think, the process of conversion from decimal number to Octal number, then we can follow the below steps:
1. Let x = 15
2. r[0] = x%8 = 7
3. x = x/8 = 1
4. r[1] = x%8 = 1;
5. x = x/8 = 0
Terminate the algorithm, we find (15)10 = (17)8 [Note: reverse r]
But if we use bit-wise operator, then it makes more interesting and efficient.



1. Let x = 15 = 1111
2. r[0] = last three bits = x&7 = 7
Explain: 
1111
0111
-------
0111  (AND)

3. x = right shift by 3 = x>>3
x = (1)
 

4. r[1] = x&7 = 1
5. x = x>>3 = 0
Terminate the algorithm, we find (15)10 = (17)8 [Note: reverse r]

Code:
  


#include<stdio.h>

int main(){
  int x=0,tx;
  char rx[12];
  int cb=0,i;
  printf("Enter a Number: ");
  scanf("%d",&x);

  tx = x;
  while(tx){
      rx[++cb] = (tx&7);
      tx = tx>>3;
  }

  printf("Result:");
  for (i=cb;i;--i)
       printf("%d",rx[i]);

  return 0;
}


Similarly we can convert a decimal number into Hexadecimal number.
1. Let x = 17
2. r[0] = last four bits = x&15 =1
Explain: 
10001
01111
-------
00001  (AND)

3. x = right shift by 4 = x>>4
x = (1)
 

4. r[1] = x&15 = 1
5. x = x>>4 = 0


Terminate the algorithm, we find (17)10 = (11)16 [Note: reverse r]

code:


#include<stdio.h>

int main(){
  int x=0,tx;
  char rx[12];
  int cb=0,i;
  printf("Enter a Number: ");
  scanf("%d",&x);

  tx = x;
  while(tx){
      rx[++cb] = tx&15;
      tx = tx>>4;
  }

  printf("Result:");
  for (i=cb;i;--i){
      if (rx[i]<9)
        printf("%d",rx[i]);
      else
        printf("%c",rx[i]+'A'-10);
  }
  return 0;
}

Analysis:if r[i] =10
rx[i] +'A' -10 = 'A'

No comments:

Post a Comment