Android Question Set binary numbers to variables in code studio

arvin

Member
How can I pass binary numbers to a variable?
like this:

Dim bb as byte
bb=0B110111

but it is not working.
 
 
Upvote 0
How can I pass binary numbers to a variable?
like this:

Dim bb as byte
bb=0B110111

but it is not working.

Until @Erel implements base-2 (binary) numeric literals, you might have to make do with either:

B4X: Copy
Dim bb as byte
bb = Bit.ParseInt("110111", 2)

or octal ? which is slightly easier to convert mentally than hexadecimal :

B4X: Copy
Dim bb as byte
bb = 067    '110 111 (leading 0 of 067 makes it octal rather than decimal) (no I am not joking)

Tbh I thought there was a Bit.FromBinaryString function to match Bit.ToBinaryString, but... apparently not. Easy enough to roll your own, though:

B4X: Copy
Sub FromBinaryString(BinStr As String) As Int
    Return Bit.ParseInt(BinStr, 2)
End Sub

or if you really, really, really need the leading "0b" to remind you that what follows is binary, then:

B4X: Copy
Sub FromBinaryString(BinStr As String) As Int
    If BinStr.ToLowerCase.StartsWith("0b") Then
        Return Bit.ParseInt(BinStr.SubString(2), 2)
    Else
        Return Bit.ParseInt(BinStr, 2)
    End If
End Sub
 
Upvote 0
Back
Top