B4J Question BCD code

Isac

Active Member
Licensed User
Longtime User
hi all,

I would like to create a bdc encoding and then also a decoding.

encoding

example: decimal 150 Binary Coded Decimal 0001 0101 0000

decoding

Binary Coded Decimal 0001 0101 0000 decimal 150

does anyone have any examples?

thank you
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
B4X:
Sub AppStart (Args() As String)
    Log(ToBCD(150))
    Log(FromBCD("000101010000"))
End Sub

Public Sub ToBCD (n As Int) As String
    Dim sb As StringBuilder
    sb.Initialize
    Do While n > 0
        Dim d As Int = n Mod 10
        sb.Insert(0, ToHex(d, 4))
        n = n / 10
    Loop
    Return sb.ToString
End Sub

Public Sub FromBCD(bcd As String) As Int
    Dim n As Int
    For i = 0 To bcd.Length - 4 Step 4
        n = n * 10 + Bit.ParseInt(bcd.SubString2(i, i + 4), 2)
    Next
    Return n
End Sub

Private Sub ToHex(n As Int, NumberOfDigits As Int) As String
    Dim res As String = Bit.ToBinaryString(n)
    Do While res.Length < NumberOfDigits
        res = "0" & res
    Loop
    Return res
End Sub

In B4i, you can use this method as alternative to ToBinaryString: https://www.b4x.com/android/forum/threads/bit-tobinarystring.46294/post-286273
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
 
Upvote 0
Top