Simple Decimal to BCD conversion function

Modified on 2019/11/23 05:08 by CaptainBoing — Categorized as: Dates, Time and Clocks, Encode and Decode, Maths

Converts a decimal number to its BCD equivalent.

e.g. 27 is returned as &h27 (39 decimal)

This is useful for writing to device registers that require BCD to hold a value rather than binary. An example here is the registers inside popular Real Time Clock chips (DS3231, etc). Consider the day-of-month register. The bottom nibble holds the units and the top nibble holds the tens. A value of 31 decimal cannot be written directly into the register as this would result in the value &h1F being written - which is illegal.

The following function takes a decimal value and returns the same positional digits as a hex number, so in the example above, 31 decimal would be returned as 31 hex (49 decimal). this would result in the legal values of 3 being written to the top nibble of the register and 1 written to the bottom nibble.

Example
Option default integer

For n=1 To 20
Print n, BCD(n),Hex$(BCD(n))
Next

The Code
	Function BCD(x As integer) As integer
		Local a$
		Local integer n,q
		a$=Str$(x)

		For n=1 To Len(a$)
			q=(q<<4) Or (Val(Mid$(a$,n,1)))
		Next
		BCD=q
	End Function

There are no checks that the number you pass will fit, use your skill and judgement