## A function to convert Decimal numbers [Range = 0 to 9999] to BCD numbers document.SUBSCRIPTION_OPTIONS = { "thing": "thread", "subscribed": false, "url": "subscribe", "icon": { "css": "fa fa-envelope-o" } };

Anobium
2013-07-03
2013-07-03
• Anobium - 2013-07-03

A little function to convert values. I needed this in preparation to display numbers on an LCD screen.

Anobium

```  Function BINtoBCD (In Decimal as Word) as word
dim Thousands as Long
dim Hundreds as Long
Dim DecimalTemp as Long
Dim l_nextnum as word
Thousands = 0
Hundreds = 0
Tens = 0
Ones = 0
DecimalTemp = 0

IF Decimal >= 1000  and Decimal < 10000  then  'Decimal is between 1000 and 10000
Thousands = Decimal / 1000

'Move to forth nibble
for localloop = 0 to 11
Rotate Thousands left Simple
next
l_nextnum  = ( Decimal / 1000 )
l_nextnum  = l_nextnum  * 4
l_nextnum  = l_nextnum  * 250
l_nextnum  = Decimal - l_nextnum
Decimal = l_nextnum
End if

IF Decimal >= 100  and Decimal < 1000  then  'Decimal is between 100 and 999
Hundreds = Decimal / 100
'Move to third nibble
for localloop = 0 to 7
Rotate Hundreds left Simple
next
l_nextnum  = ( Decimal / 100 ) * 100
l_nextnum  = Decimal - l_nextnum
Decimal = l_nextnum
End if

IF Decimal >= 10  and Decimal < 100 then  'Decimal is between 10 and 99
DecimalTemp = Decimal / 10
Tens = DecimalTemp * 16  'Move to high nibble
Decimal = Decimal - DecimalTemp * 10
End if

If Decimal >= 0 and Decimal < 10  Then  'Decimal is between 0 and 9
Ones = Decimal
End if

l_nextnum = Thousands + Hundreds + Tens + Ones
BINtoBCD = l_nextnum
End sub
```

• Anobium - 2013-07-03

Kent,

I updated your code. Thank you.

Can this be optimized?
And, the code at

```  l_nextnum  = ( Decimal / 1000 )
l_nextnum  = l_nextnum  * 4
l_nextnum  = l_nextnum  * 250
l_nextnum  = Decimal - l_nextnum

I wanted to do... but, I get a lockup of the processor.  Any ideas why?

l_nextnum  = ( Decimal / 1000 ) * 1000)
l_nextnum  = Decimal - l_nextnum
```