﻿ Convert decimal number to hexadecimal ~ Programming Tutorials by SourceTricks
Wednesday, July 11, 2012

Convert decimal number to hexadecimal

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`

Name

Email *

Message *