Kyle Martin
Kyle Martin

Reputation: 94

Assembly - Convert Character Array to Interger

RAX points at a string of numbers terminated by an exclamation point (ex. "1234!"). I've been trying to convert this sting of numbers to an actual number, but it's doing same really weird things... Here's the code:

CHARINT:                ; convert ASCII encoded numbers to an actual number
 XOR RCX,RCX                    ; clear RCX for use - running total
 .LOOP:                         ; set loopback point
 CMP BYTE [RAX],33              ; if we're on our terminating character, end
 JE .DONE

 PUSH RAX                       ; multiply our previous number by ten to make room for the next digit
  MOV RAX,RCX
  MOV RCX,10
  MUL RCX
  MOV RCX,RAX
 POP RAX

 SUB BYTE [RAX],0x30            ; convert from ASCII
 ADD RCX,[RAX]                  ; add our most recent digit

 INC RAX                        ; next digit

 JMP .LOOP
 .DONE:
 MOV RAX,RCX
RET

For some reason, when I ask it to print the values of RAX during each iteration the numbers follow a fascinating sequence that Wolfram Alpha has quite a bit to say about...

Anyways, I know that I am probably missing something extremely simple and I would greatly appreciate it if someone would point it out to me. Thank you!

-Kyle

Upvotes: 1

Views: 42

Answers (2)

rkhb
rkhb

Reputation: 14409

A quick'n'dirty solution:

Change

SUB BYTE [RAX],0x30            ; convert from ASCII
ADD RCX,[RAX]                  ; add our most recent digit

(which adds not only one byte but the whole 8-byte-64-bit-bunch)

to

SUB BYTE [RAX],0x30            ; convert from ASCII
MOVZX RDX, BYTE [RAX]          ; load one byte into a 64-bit register
ADD RCX,RDX 

Upvotes: 1

David Wasser
David Wasser

Reputation: 95626

I'm gonna stick my neck out and opine that

ADD RCX,[RAX]

is not adding the BYTE at [RAX} to RCX, but is probably adding a lot more than 8 bits from that memory address.

Upvotes: 2

Related Questions