convert Decimal to Hexidecimal number

WallyKid

Senior member
Oct 10, 1999
692
0
0
I understand the basics that Decimal is base 10, and hexidecimal is base 16. However, i wonder if there is a method to derive manually without listing all possible combinations, for the 4002 base 10 in base 16 format. Anyone?
 

FrankSchwab

Senior member
Nov 8, 2002
218
0
0
Are you asking how to write a function that converts a number like 4002 from base-10 to base-16? Sounds like a first-quarter programming class assignment to me.

You'd need to read the input number into a binary format (Integer, for example).
You'd need to break your input data up into 4-bit chunks.
__You'd need to write a routine that converts a 4-bit chunk into a character in the set (0..9, A..F).
____if the value of the 4-bit chunk was less than 10, you'd do one conversion (to 0..9), otherwise you'd do a different conversion (to A..F).
You'd need to correctly assemble the returned characters.
You'd need to write the output.

And, you'd probably want to ask this question in the Software forum, unless I completely misunderstood your request.

/frank
 

RossGr

Diamond Member
Jan 11, 2000
3,383
1
0
A nice simple algorithm is to simple divide the base 10 number by the number of the base you wish to convert to. The remainder of the firstt division yields the least siginificant digit, the remainder of each successive division yields an additional digit.

so

4002/16 = 250 R 2

250/16 = 15 R 10

15/16 = 0 R 15

Take the remainders you get FA2

This works for any number base.
 

glugglug

Diamond Member
Jun 9, 2002
5,340
1
81
Like this?

#include <iostream>
#include <manip>
using namespace std;

int main(int argc, char *argv[])
{
int num;
cout << "Enter base 10 number: ";
cin >> num;
cout << "\nHex version: " << ios::hex << num << "\n";
}
 

Peter

Elite Member
Oct 15, 1999
9,640
1
0
The fundamental thing to understand is you're converting strings here, not numbers.
First you convert the original string of digits into an integer number by calculating digit value left to right, accumulating in a variable.

Then you convert to a string by a series of divisions by the new base, the remainder of each division giving you a digit. (Note that the 2nd step gives you the least significant digit first.)

Example: 4C53 hex converted to octal (numbers shown are decimal)

"4C53"

"4"
4 * 16 + "C" = 76
76 * 16 + "5" = 1221
1221 * 16 + "3" = 19539

19539 / 8 = 2442 r 3 -> "3"
2442 / 8 = 305 r 2 -> "23"
305 / 8 = 38 r 1 -> "123"
38 / 8 = 4 r 6 -> "6123"
4 / 8 = 0 r 4 -> "46123"

result: "46123"
 

WallyKid

Senior member
Oct 10, 1999
692
0
0
Thanks for all the very helpful feedbacks and solutions. Thats what i need. THanks.

 

Amorphus

Diamond Member
Mar 31, 2003
5,561
1
0
in working with multiple bases, there is only one correct answer. the only way you get alternate answers is when you don't simplify properly. (i.e., divide by the wrong number)