Click to See Complete Forum and Search --> : convert a number to a hexadecimal


scifire
10-10-2003, 01:51 PM
i must write a program in C/C++ tha do that but in fact i need a good book for computer algorithms can somebody recommed me (e-book or on-line tutorial or whatever it is ):) concerning the algorithms
my idea for the problem is that furst i convert the number to binary (i can do it ) and then it is simple to do the binary->hexadecimal convertion but i think this is not the more flexible way to do that

bryan.6
10-10-2003, 02:04 PM
well, first of all, i would suggest printf("%x", num) but i'm sure that's not what you are looking for.
you know how to convert decimal to binary? i belive you would use the same idea except with num % 16; instead of a num % 2; (whenever you do taht in your code) but then you probably have to make this either a number or a-f.
just my ideas on things, i can't vouch that these are right.

scifire
10-11-2003, 01:57 PM
%16 can't solve the problem like you say there must have in mind that you have the a-f letters :( and i can't do it
but like i say i can do binary convertion and the hexadecimal but i don't know what will be the face of my prof :D

bwkaz
10-11-2003, 07:04 PM
Use %x, not %16. Don't substitute anything for the x, just use x. It'll get printed in hexadecimal.

Tell the prof you found it in the printf manual (but read man 3 printf first).

stoe
10-12-2003, 07:37 PM
nothing earth-shattering here ...


#include <string>
#include <cstdlib>
#include <algorithm>
#include <iostream>

const char CONV_TABLE[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};

void UnsignedToHexString(unsigned val, std::string &outStr)
{
div_t result;

result.quot = val;
outStr = "";

do {
result = div(result.quot, 16);
outStr += CONV_TABLE[result.rem];
} while(result.quot != 0);

std::reverse(outStr.begin(), outStr.end());
}

int main(void)
{
std::string result;
UnsignedToHexString(65535, result);
std::cout << result << std::endl;
}