Wednesday, July 11, 2012

Write a program to convert decimal number to hexadecimal

The approach:-
  1. Initialize a string array to hold the output hexadecimal string.

  2. mod the input number by 16.  Map a hexadecimal digit based on the reminder value and append the output string.

  3. Divide the number by 16 for next iteration.

  4. Repeat steps 2 and 3 till number becomes 0.

  5. Reverse the string to get the output hexadecimal sequence.

C++ program to convert decimal number to hexadecimal string

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;

char* dec2hex(int n) {
 char* str = (char*)malloc(sizeof(32));
 char* hex_str = "0123456789abcdef";

 int count = 0;
 while ( n > 0 ) {
  int rem = n % 16;
  n = n / 16;
  str[count] = hex_str[rem];
  count++;
 }
 str[count] = '\0';

 // reverse the string
 int size = strlen(str) - 1;
 for ( int i = 0; i <= size/2; i++ ) {
  char ch = str[i];
  str[i] = str[size - i];
  str[size - i] = ch;
 }

 return str;
}

int main() {
 int n = 100;
 cout << dec2hex(n) << endl;
}

Output:-
64

1 comment :

  1. Simpler code is here and it works

    #include
    using namespace std;

    int main(void){

    int i,sum = 0,dec=100,shift,val;
    char str[10];
    char *look="0123456789ABCDEF";
    shift = 8 * sizeof(dec)-4;
    i = 0;
    while (shift >= 0){
    val = (dec >> shift) & 0xf;
    str[i] = look[val];
    i++;
    shift -= 4;
    }
    str[i] = '\0';
    cout << "Hex number is 0x " << str<< endl;

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top