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
why is this? It's because there's a bug in your code. It's of a rather common variety, too: a missing pair of (parentheses).
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.