April 17th, 2003, 09:57 PM

ascii to hex
im having a real hard time converting a string of char's to the hex equivalent. lets say i have:
void main()
{
char x = 'A';
_asm
{
mov AL, x
mov x, AL
}
_putch(x);
}
i disassemble and of course, AL contains 41, the hex equivalent of 'A'. but when i put the char, it outputs 'A'. i tried doing:
cout << hex << x;
but that doesnt work either. i know this can be done in assembly, i DONT want to write this out with some gigantic switch statement, anyone help plz?
April 17th, 2003, 10:28 PM

Two things have come out of Berkeley, Unix and LSD.
It is uncertain which caused the other.
April 17th, 2003, 10:57 PM

heh, with this ugly piece of code i have accomplished it, but i'll check out that link.
int m;
while((m = cin.get()) != '\n')
{
cout << setbase(16) << m << "%";
}
edit: awww, man... i didnt even think to do that blatantly obvious, lol. uhhduhh, printf(). :rolleyes: . but just out of curiosity, if i was some deranged maniac who was obsessed with assembly, how would i do it that way? a long time ago i wrote a hex to binary/hex to ascii calculator, but i cant seem to work it backwards. the way i did it was rotating > masking > add 30h >etc... this seems like it should be ez since it's already sitting right there in the register in hex...?
Last edited by infamous41md; April 17th, 2003 at 11:03 PM.
April 18th, 2003, 10:04 AM

It's not easy because it's "sitting in the register as hex". It's a number. It's not stored in any certain base (well, I guess it's physically stored in binary, but this doesn't make any difference to your code  it might as well be store in decimal). So, you have to think of it as just a number (whether it's hex or decimal or binary or octal, etc). To get it in hex form, you must convert it into a string of hex characters (just as printf needs to convert it into a string of decimal characters to show it to the display). You can do this by grabbing the low 4 bits (x & 15), which is a number from 0..15  this is the least significant digit. 0..9 should be outputted as '0'..'9' (i.e. ascii 48..57), 10..15 should be outputted as 'A'..'F' (i.e. ascii 65..70). Then move all the bits over 4 (x shr 4), so you can repeat the process.
Note that if you weren't doing this for an even computer base (i.e. base = 2^n, n=integer), for example, if you were doing it in decimal base10, you would need to use (x % 10) and (x / 10) for getting the last digit, and shifting the number over 1 digit, which involves division (modulus is also a division), which is VERY slow. Because you are converting to base16, this can be sped up as (x % 16) = (x & 15), and (x / 16) = (x shr 4). The bitwise & and shr instructions are very fast (shr is >> in C/C++, btw).
I hope this helps.