This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

ASCII to BCD conversion

I am trying to use the following code to convert 2 digit ASCII numbers to BCD number, for setting RTC Clock DS1307.


unsigned char ASCII_TO_BCD(unsigned char ascii_text[2])
{
        unsigned char bcd_value;
        ascii_text[0] &= 0x0F;     // set high nibble(3) to 0 (may not be needed)
        ascii_text[0] <<= 4;       // shift lower nibble to higher

        ascii_text[1] &= 0x0F;     // set high nibble(3) to 0 (may not be needed)
        bcd_value = ascii_text[0] | ascii_text[1];  // mix both to get BCD
        return bcd_value;
}

When I pass '12' to the function, 0x33 is returned instead of 0x12. Is something wrong in this code? Thanks.

Parents
  • Now if you only use digits (0..9) - why then did you suddenly include the one line that makes use of character 'a' and was intended for the hexadecimal range 'a' .. 'f'?

    Next thing - the guy who did give you example code does something I don't like:

    bcd_value = ( ascii_text[0] - 48)  << 4 ; // 48 for '0' ASCII offset
    


    ascii_text contains characters ('0', '1', ... '9')
    48 is a magic number that requires the comment "48 for '0' ASCII offset".

    So a comment is explicitly needed just because the code is mixing between characters and the ordinal numbers of characters.

    It is way better to write:

    bcd_value = ( ascii_text[0] - '0')  << 4 ;
    


    Suddenly, no comment is needed since there is no longer any magic value 48 to explain.

    There is a big reason why the C language allows us to perform mathematical operations directly using characters.

Reply
  • Now if you only use digits (0..9) - why then did you suddenly include the one line that makes use of character 'a' and was intended for the hexadecimal range 'a' .. 'f'?

    Next thing - the guy who did give you example code does something I don't like:

    bcd_value = ( ascii_text[0] - 48)  << 4 ; // 48 for '0' ASCII offset
    


    ascii_text contains characters ('0', '1', ... '9')
    48 is a magic number that requires the comment "48 for '0' ASCII offset".

    So a comment is explicitly needed just because the code is mixing between characters and the ordinal numbers of characters.

    It is way better to write:

    bcd_value = ( ascii_text[0] - '0')  << 4 ;
    


    Suddenly, no comment is needed since there is no longer any magic value 48 to explain.

    There is a big reason why the C language allows us to perform mathematical operations directly using characters.

Children