edofbrighton
Member
hello,
I'm trying to convert an 8-bit number into to bcd, packed or unpacked it doesn't matter how it's done. I'm using this code, but i can't get it to work. Can anyone tell me where i'm going wrong, or direct to me to some code that works.
I'm trying to convert an 8-bit number into to bcd, packed or unpacked it doesn't matter how it's done. I'm using this code, but i can't get it to work. Can anyone tell me where i'm going wrong, or direct to me to some code that works.
Code:
MOVLW B'00000111'
MOVWF BINARY
CALL BIN2BCD
MOVF TENS_AND_ONES
ANDLW B'00001111'
CALL LOOKUP_TABLE
CALL DISPLAY
RRF TENS_AND_ONES,4
MOVF TENS_AND_ONES,W
CALL LOOKUP_TABLE
CALL DISPLAY
GOTO $
BIN2BCD:
CLRF HUNDREDS
SWAPF BINARY,W ; swap the nibbles
ADDWF BINARY, W ; so we can add the upper to the lower
ANDLW B'00001111' ; lose the upper nibble (W is in BCD from now on)
BTFSC STATUS,DC ; if we carried a one (upper + lower > 16)
ADDLW 0x16 ; add 16 (the place value) (1s + 16 * 10s)
BTFSC STATUS,DC ; did that cause a carry from the 1's place?
ADDLW 0x06 ; if so, add the missing 6 (carry is only worth 10)
ADDLW 0x06 ; fix max digit value by adding 6
BTFSS STATUS, DC ; if was greater than 9, DC will be set
ADDLW -0x06 ; if if it wasn't, get rid of that extra 6
BTFSC BINARY,4 ; 16's place
ADDLW 0x16 - 1 + 0x6 ; add 16 - 1 and check for digit carry
BTFSC STATUS, DC
ADDLW -0x06 ; if nothing carried, get rid of that 6
BTFSC BINARY, 5 ; 32nd's place
ADDLW 0x30 ; add 32 - 2
BTFSC BINARY, 6 ; 64th's place
ADDLW 0x60 ; add 64 - 4
BTFSC BINARY, 7 ; 128th's place
ADDLW 0x20 ; add 128 - 8 % 100
ADDLW 0x60 ; has the 10's place overflowed?
RLF HUNDREDS, F ; pop carry in hundreds' LSB
BTFSS HUNDREDS, 0 ; if it hasn't
ADDLW -0x60 ; get rid of that extra 60
MOVWF TENS_AND_ONES ; save result
BTFSC BINARY,7 ; remeber adding 28 - 8 for 128?
INCF HUNDREDS, F ; add the missing 100 if bit 7 is set
RETURN ; all done!