News:

MASM32 SDK Description, downloads and other helpful links
MASM32.com New Forum Link
masmforum WebSite

ASCII to HEX

Started by georgek01, July 14, 2009, 10:54:14 AM

Previous topic - Next topic

georgek01

Hello!

I've recently needed the hex number of a string representation of a hex value e.g. '2A' = 2A

I searched this forum and found quite a lot of examples on how to convert ASCII to HEX. I tried some of the code in my app but couldn't get it working. Not being very good at ASM i gave up on trying to adapt the code. I then came up with my own "simpler" version.

I build a hex string from a counter variable, them compare the two strings. If the strings are the same my counter variable is the value I'm looking for.



szHex   db '%X',0      ; format-control string
bHex    db 4 dup (?)  ; buffer to hold the temp hex string
hexasci db 4 dup (?)  ; buffer holds the hex string i want the hex value of
dwHex   dword ?       ; variable to be used as a hex counter


ASC2HEX proc

  ; increment a counter (dwHex), use wsprintf to fill
  ; a temp buffer with the hex value. compare this
  ; buffer to the hex buffer that holds the original
  ; hex string. if the strings are the same, dwHex is
  ; the value of the ASCII representation.

  mov dwHex,0

  hexstart:

  invoke wsprintf, addr bHex, addr szHex,dwHex
  invoke lstrcmp, addr bHex, addr hexasci

  .if eax == 0 ; found hex
    jmp hexend
  .else
    inc dwHex
    .if dwHex > 0FFh ; string not within range 0h to 0FFh
        jmp hexerr
    .endif
    jmp hexstart
  .endif

  hexend:

  ; dwHex is the hex value representation of buffer hexasci
 
  hexerr:

  ; string not within range 0h to 0FFh

  xor eax,eax

ASC2HEX endp



I have not tested this on large numbers as my requirement is for values between 0h and 0FFh.
What we have to learn to do, we learn by doing.

- ARISTOTLE (384-322 BC)

dedndave

well - the masm32 library has the uhex$ function

mov eax,90ABCDEFh
print uhex$(eax),13,10
exit

here is a routine that does a decent job if you don't want to use the library
http://www.masm32.com/board/index.php?topic=11429.msg85142#msg85142

dedndave

ohhhhhhhhhhhhhhh
you want to go the other way - lol
what you want is hex2bin (i.e. you are converting to binary - not hex)
searching that may yield better results
the masm32 library has hval - it can convert 8-character zero terminated ascii hex strings to 32-bit binary (returns in eax)

include \masm32\include\masm32rt.inc
.data
szHex db '90ABCDEF',0
.data?
H2Bin dd ?
.code
_main proc
mov H2Bin,hval(addr szHex)
print uhex$(eax),13,10
inkey
exit
_main endp
end _main

the masm32\help folder has several chm files - have a look at all of them - hval and uhex$ are in hlhelp.chm

georgek01

Thanks dedndave. I'll give that one a try too.
What we have to learn to do, we learn by doing.

- ARISTOTLE (384-322 BC)