Hex to BCD conversion

25.6k views Asked by At

To convert (213AFE)H to BCD, first it has to be converted to binary which gives (2177790)D. Now each digit is converted to its BCD code which gives (0010 0001 0111 0111 0111 1001 0000)BCD.

Another way is to convert the hex value to binary which gives (0010 0001 0011 1010 1111 1110)B and then do BCD adjust by adding 6 to each digit greater than 9 as follows:

0010 0001 0011 1010 1111 1110
+              0110 0110 0110
-----------------------------
0010 0001 0100 0001 0110 0100 -> 35092368D

The final result in the processes above are different. Is the second method wrong? Why?

4

There are 4 answers

0
Pjman Yucifee On

here is a C function to convert uint32 to BCD and store it in array so respectively in decimal format. Note that defined 'len' is maximum length of data type in decimal format therefore uint32 full value represent 4,294,967,295 that make 10 digit

#define len 10
void BCD(uint32_t value, uint8_t bcd[len])
{
    uint32_t factor;
    uint32_t decimal = len;
    uint32_t remains = value;
    for(uint8_t i = 0; i < decimal; ++i)
    {
        factor = 1;
        for (uint8_t j = 0; j < (decimal - i - 1); ++j)
            factor *= 10;
        bcd[decimal - i - 1] = remains / factor;
        remains = remains % factor;
    }
    return;
}

1
Ganesh Makkina On

Ascii_Hex:                          ;procedure to convert Ascii to Hex
 mov rax,0
 mov rcx,4
 mov rsi,hex
 mov rbx,0
   loop1:
    rol bx,4
    mov al,[rsi]
    cmp al,'9'
    jbe sub30h
    sub al,7h
      sub30h:
       sub al,30h
       add bx,ax
    inc rsi
 loop loop1
ret

HtB:                                ;procedure to convert HEX to BCD
   io 1,1,msg,msglen
 io 0,0,hex,5
 call Ascii_Hex                   ;call to procedure to convert ascii to hex
 mov rcx,5
 mov ax,bx                     
 mov bx,0Ah
   loop2: 
    mov rdx,0
    Div bx                        
    push dx
 loop loop2
 
 mov rsi,hex
 mov rcx,5
   loop3:
    pop dx
    add dl,30h
    mov[rsi],dl
    inc rsi
 loop loop3 
 io 1,1,hex,5
 io 1,1,newline,1
ret

0
user7591025 On

The Second method is not WRONG but it is actually part of the main method for conversion i.e. the number greater than 9 should always be adjusted by BCD adjust method (by adding 6) the answer that you get from it is a valid BCD !

0
Josko Marsic On

I use this code for 1byte conversion from hex to BCD in the C language and it works only for 0-99d. If you need 2byte, word, procedure are similar.

For example, it converts 78d(0x4E) => 0x78

uint8 convert2BCD(uint8 hexData)
{
    uint8    bcdHI=hexData/10;
    uint8    bcdLO=hexData%10;
    uint8    bcdData= (bcdHI<<4)+bcdLO;    

    return   bcdData;
  }