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
  • I am also not getting why my code(which I posted) was not working. Anyway, THANK YOU VERY MUCH.

    Try some other arguments besides "12", and maybe you'll notice a pattern...

    It fails because of the difference between what you think an array-type function argument as in

    void func(int in[2])
    

    does, and what actually happens. You believe this behaves vaguely like

    void func(int in1, int in2)
    

    while it really is equivalent to

    void func(int *in)
    

    I'll also venture an educated guess that in the actuall call of your function, which you didn't show, the argument is a string literal, i.e. it looks like this:

    result = asciitobcd("12");
    

    , and that changing the call to

    { unsigned char tempstr[] = "12"; result = asciitobcd(temp);}
    

    magically cures it.

    A note to the experts in here: please don't spoil the OP's a-ha! experience. Let him figure this one out for himself.

Reply
  • I am also not getting why my code(which I posted) was not working. Anyway, THANK YOU VERY MUCH.

    Try some other arguments besides "12", and maybe you'll notice a pattern...

    It fails because of the difference between what you think an array-type function argument as in

    void func(int in[2])
    

    does, and what actually happens. You believe this behaves vaguely like

    void func(int in1, int in2)
    

    while it really is equivalent to

    void func(int *in)
    

    I'll also venture an educated guess that in the actuall call of your function, which you didn't show, the argument is a string literal, i.e. it looks like this:

    result = asciitobcd("12");
    

    , and that changing the call to

    { unsigned char tempstr[] = "12"; result = asciitobcd(temp);}
    

    magically cures it.

    A note to the experts in here: please don't spoil the OP's a-ha! experience. Let him figure this one out for himself.

Children
No data