problem with bcd and a number

Ethan Furman ethan at stoneleaf.us
Thu Aug 4 21:44:41 CEST 2011

```nephish wrote:
> Hey all,
>
> I have been trying to get my head around how to do something, but i am
> missing how to pull it off.
> I am reading a packet from a radio over a serial port.
>
> i have " two bytes containing the value i need.  The first byte is the
> LSB, second is MSB.  Both bytes are BCD-encoded, with the LSB
> containing digits zX and MSB containing digits xy.  The system speed
> is then xyz%, where 100% means maximum speed and would be given by
> bytes 00(LSB) 10(MSB)."
>
> that is a quote from the documentation.
> Anyway, i am able to parse out the two bytes i need, but don't know
> where to go from there.
>
> thanks for any tips on this.

As I recall, when you cut a byte in half you get two nibbles.  You need
something like this:

8<--- bcd.py ----------------------------------------------------------
def bcd_to_int(msb, lsb):
"""msb has two decimal digits, lsb has one
e.g. msb has xy=10, lsb has zX = 00, actual number (xyz)
is 100"""
ones = lsb >> 4
tens = msb & 0x0f
hundreds = msb >> 4
if ones > 9 or tens > 9 or hundreds > 9:
raise ValueError(
"invalid BCD digits in %02x %02x" % (msb, lsb)
)
tens *= 10
hundreds *= 100
answer = hundreds + tens + ones

if __name__ == '__main__':
import unittest

class Test_BCD(unittest.TestCase):
def test_valid(self):
msb = 0x09
lsb = 0x34  # 4 will be discarded as garbage
self.assertEqual(bcd_to_int(msb, lsb), 93)
def test_invalid(self):
msb = 0x1a
lsb = 0x10
self.assertRaises(ValueError, bcd_to_int, msb, lsb)

unittest.main()
8<---------------------------------------------------------------------

Hope this helps.

~Ethan~

```