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

Converting from BCD

So I have to convert a number from BCD, however when I do it like this:

((X>>4)*10) + X&0xF

It comes out a wrong number, however if I do this:

int H = x>>4;
int L = x&0xF;
return H*10 + L;

it goes just right
why is this?

for an example, I converted 16 to BCD(stays 0x16) and when I execute the 1st code it outputs 0

Parents
  • To write higher quality code, you need more than just the parentheses.You got to make sure that X shuffled is not bigger than what you expect. Some people sensibly refer to it as defensive programming.

    You could go a whole lot more and make sure that each of the two digits of the packed BCD (and this is referring to packed BCD) is no more than 9.

    (((X>>4)&0xF)*10)+(X&0xF)
    

    For further details of this and many other useful snippets, just visit my blog.

Reply
  • To write higher quality code, you need more than just the parentheses.You got to make sure that X shuffled is not bigger than what you expect. Some people sensibly refer to it as defensive programming.

    You could go a whole lot more and make sure that each of the two digits of the packed BCD (and this is referring to packed BCD) is no more than 9.

    (((X>>4)&0xF)*10)+(X&0xF)
    

    For further details of this and many other useful snippets, just visit my blog.

Children
No data