Decimal to binary conversion
Weeee! My 1st useful contribution to this forum (a welcome change from my habitual leeching and strolling about in left field).
Here are code snippets to change a decimal 5 digit array into a binary 2 byte field (I use it as an address for external memory EEPROMs).
Note: The digits are reversed and the results are concatenated in NUMHI and NUMLO.
Robert
:)
DATAIN VAR BYTE[5]
DIGIT0 VAR BYTE
DIGIT1 VAR BYTE
DIGIT2 VAR BYTE
DIGIT3 VAR BYTE
DIGIT4 VAR BYTE
BCD48 CON %00110000
NUMHI VAR BYTE
NUMLO VAR BYTE
DIGIT4 = DATAIN[0] - BCD48
DIGIT3 = DATAIN[1] - BCD48
DIGIT2 = DATAIN[2] - BCD48
DIGIT1 = DATAIN[3] - BCD48
DIGIT0 = DATAIN[4] - BCD48
ASM
; 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)
;
; ALTERATIONS:
; - variables and label prefixed with "_" to suit MPASM requirements.
; - variables renamed to suit individual requirements.
; - some instructions substituted to suit MPASM requirements.
_DEC2BIN
movf _DIGIT1,W ; (D1 + D3) * 2
addwf _DIGIT3,W
movwf _NUMLO
rlf _NUMLO,F
swapf _DIGIT2,W ; + D2 * 16 + D2
addwf _DIGIT2,W
addwf _NUMLO,F
rlf _DIGIT4,W ; + (D4 * 2 + D3) * 256
addwf _DIGIT3,W
movwf _NUMHI
rlf _NUMLO,F ; * 2
rlf _NUMHI,F
swapf _DIGIT3,W ; - D3 * 16
subwf _NUMLO,F
BTFSS 3,0 ; SKPC (not supported in MPASM
decf _NUMHI,F
swapf _DIGIT2,W ; + D2 * 16 + D1
addwf _DIGIT1,W
addwf _NUMLO,F
BTFSC 3,0 ; SKPNC (not supported in MPASM
incf _NUMHI,F
swapf _DIGIT4,W ; + D4 * 16 + D0
addwf _DIGIT0,W
rlf _NUMLO,F ; * 2
rlf _NUMHI,F
addwf _NUMLO,F
BTFSC 3,0 ; SKPNC (not supported in MPASM
incf _NUMHI,F
movf _DIGIT4,W ; - D4 * 256
subwf _NUMHI,F
swapf _DIGIT4,W ; + D4 * 16 * 256 * 2
addwf _NUMHI,F
addwf _NUMHI,F
return ; Q.E.D.
ENDASM