Write a program to convert decimal number to hexadecimal
The approach:-- Initialize a string array to hold the output hexadecimal string.
- mod the input number by 16. Map a hexadecimal digit based on the reminder value and append the output string.
- Divide the number by 16 for next iteration.
- Repeat steps 2 and 3 till number becomes 0.
- 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
0 comments:
Post a Comment