Can anyone give me an idea how to convert an int or decimal number into hexadecimal? I know how to do it for binary by dividing by 2 and using the modulus % operator, but how do you take into account a b c d e f if the integer is greater than 9? any ideas would greatly be appreciated.

Dani AI

Generated

asked how to handle digits > 9; 's recursive idea is solid but a couple of practical points are worth adding: always handle zero as a special case (a recursion that only prints while n != 0 will produce no output for 0), decide whether you want uppercase or lowercase hex letters, and use an unsigned type (or print a leading '-' then convert) so negative inputs don't confuse bit/shift operations. For quick, reliable conversions in real code prefer the standard library; for learning, a short manual routine is instructive.

A compact, idiomatic C++ approach using streams (no manual digit mapping) is simple and safe:

#include <sstream>
#include <iomanip>

std::string to_hex(unsigned long v, bool uppercase = false) {
    std::ostringstream oss;
    if (uppercase) oss << std::uppercase;
    oss << std::hex << v;
    return oss.str();
}

For a minimal manual routine (illustrates how to map 10-15 to letters without a lookup string), build the hex digits from least significant to most and reverse at the end:

#include <string>
#include <algorithm>

std::string to_hex_manual(unsigned long v, bool uppercase = false) {
    if (v == 0) return "0";
    std::string out;
    while (v) {
        unsigned d = v & 0xF;                         // digit = v % 16
        char c = (d < 10) ? ('0' + d) : (uppercase ? 'A' : 'a') + (d - 10);
        out.push_back(c);
        v >>= 4;                                      // divide by 16
    }
    std::reverse(out.begin(), out.end());
    return out;
}

Notes: printf/scanf-style %x/%X or std::to_chars (C++17) are alternatives (std::to_chars is fastest). If you keep the recursive style from , ensure you print a "0" for input 0 before recursing and use unsigned arithmetic or handle the sign explicitly.

Recommended Answers

All 7 Replies

thanks guys, now for the challenge, how would i convert an int to hexadecimal, using recursion, in other words write a recursive function, i know how to do it for base 2, but how do you accomdate for the letters a-f if the digits are greater than 9?

>but how do you accomdate for the letters a-f if the digits are greater than 9?
Use a string:

static const string hex ( "0123456789ABCDEF" );

This is a simple problem once you figure it out. The function shouldn't need to be more than 4 or 5 logical lines.

This is what i'm trying to do but am not sure how to convert it if it is > 9 to a b c d e or f?

Here is the code thus far:

#include <iostream>
using namespace std;
#include "prompt.h"

// recursion: print English form of each digit
// in an integer: 123 -> "one two three"

void PrintDigit(int num)
// precondition: 0 <= num < 10
// postcondition: prints english equivalent, e.g., 1->one,...9->nine     
{
    if (0 == num)       cout << "zero";
    else if (1 == num)  cout << "one";
    else if (2 == num)  cout << "two";
    else if (3 == num)  cout << "three";
    else if (4 == num)  cout << "four";
    else if (5 == num)  cout << "five";
    else if (6 == num)  cout << "six";
    else if (7 == num)  cout << "seven";
    else if (8 == num)  cout << "eight";
    else if (9 == num)  cout << "nine";
    else cout << "?";
}

void Print(long int number)
// precondition: 0 <= number
// postcondition: prints English equivalent of number
{
	
	if(0 <= number && number < 16)
	{
		PrintDigit(int(number));
	}
	else
	{
		Print(number /16);
		cout << " ";
		PrintDigit(int(number % 16));
	}
	
		
}

int main()
{
	long number = PromptRange("enter an integer",0L,1000000L);
    Print(number);
    cout << endl;
    
    return 0;
}

not sure how to test if digit > 9 to print the appropriate letter a = 10 b =11
...f = 15.


<< moderator edit: added [code][/code] tags >>

You're still thinking in base ten. Start thinking in base sixteen and things will be easier:

#include <iostream>
#include <string>

using namespace std;

void print_hex ( int dec )
{
  static const string hex_dig ( "0123456789ABCDEF" );

  if ( dec != 0 ) {
    print_hex ( dec / 16 );
    cout<< hex_dig[dec % 16];
  }
}

int main()
{
  cout<<"0x";
  print_hex ( 27 );
  cout<<endl;
}

thanks everyone for your help, igot this one figured out.
you can delete or dis reguard this thread.

>igot this one figured out
I sure hope so, seeing as how I gave you a complete solution.

>you can delete or dis reguard this thread
Threads don't get deleted when the problem is solved. That defeats the purpose of the search function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.