EmbeddedRelated.com
Forums

decimal to binary routine does not provide correct result

Started by Ken Stuempges February 6, 2009
The attached routine by Peter Hemsley, March 2003, does not return the
correct conversion. As an example I am trying to convert decimal 12345
to binary, and it returns hex 31 in the high byte and hex D4 in the
low byte. I checked several on-line converters and they all return
the answer hex 31 in the high byte and hex 39 in the low byte. I
am using MPLAB ver 8.1, and am using a PICKit 2 in debug run the
program and to check the result. To test it I just added a couple of
lines to pre-load the numbers. Here is the listing . . .

; 5 digit decimal to 16 (17) bit binary. By Peter Hemsley, March
2003.
; Input decimal digits in D0 (LSD) to D4 (MSD)
; Output 16 bit binary in NUMHI and NUMLO
; No temporary variables required
; Code size: 33 instructions
; Execution time: 33 cycles (excluding Call and Return)
; Returns carry set if > 65535 (and NUMHI-LO MOD 65536)

LIST pF870 ;tell assembler what chip we are using
include "P16F870.inc" ;include the defaults for the chip
ERRORLEVEL 0, -302 ;suppress bank selection messages
__config 0x3F71 ;sets the configuration settings (oscillator type etc.)

cblock 0x20
NUMLO
NUMHI
D0
D1
D2
D3
D4
endc

org 0x00

; dec2bin16

movlw 0x01
movwf D0
movlw 0x02
movwf D1
movlw 0x03
movwf D2
movlw 0x04
movwf D3
movlw 0x05
movwf D4
movf D1,W ; (D1 + D3) * 2
addwf D3,W
movwf NUMLO
rlf NUMLO,F

swapf D2,W ; + D2 * 16 + D2
addwf D2,W
addwf NUMLO,F

rlf D4,W ; + (D4 * 2 + D3) * 256
addwf D3,W
movwf NUMHI

rlf NUMLO,F ; * 2
rlf NUMHI,F

swapf D3,W ; - D3 * 16
subwf NUMLO,F
skpc
decf NUMHI,F

swapf D2,W ; + D2 * 16 + D1
addwf D1,W
addwf NUMLO,F
skpnc
incf NUMHI,F

swapf D4,W ; + D4 * 16 + D0
addwf D0,W

rlf NUMLO,F ; * 2
rlf NUMHI,F

addwf NUMLO,F
skpnc
incf NUMHI,F

movf D4,W ; - D4 * 256
subwf NUMHI,F

swapf D4,W ; + D4 * 16 * 256 * 2
addwf NUMHI,F
addwf NUMHI,F

loop
goto loop

end
NUMHI returns hex 31 and NUMLO returns hex D4. All I used was the
cblock and simple move instructions to load the values.

I really need a routine like this to convert 5 digit decimal to binary
. . .

HELP

Ken