B4J Code Snippet Binary code and Gray Code

Didn't find any Gray Code encoding on the forums, so I leave these two procedures for everyone to use:

B4X:
Public Sub Number2GrayCode(a As Int) As String
    Dim b As Int = Bit.Xor(Bit.Shiftright(a,1),a)
    Return Bit.ToBinaryString(b)
End Sub

Public Sub Number2BinaryCode(a As Int) As String
    Return Bit.ToBinaryString(a)
End Sub
 
Hi,

Thanks for sharing such a nice and smart code which solve my problem in just one line.
Now I get standard binary from a byte or integer but it does not include trailing Zero...
i.e. if number value is 31 and binary code is 00011111 but it return string value with only 11111.
So can we get return whole 8bit binary string including Zero and also in 16bit mode also. Thanks.
 

emexes

Expert
Licensed User
Simple way:

B4X:
Sub ZeroPadLeft(S As String, L As Int) As String

    Dim Temp As String = S
   
    Do While Temp.Length < L
        Temp = "0" & Temp
    Loop
   
    Return Temp
   
End Sub
 

TILogistic

Expert
Licensed User
Longtime User
or B4XFormatter
B4X:
Public Sub testbinary
    Log(FormatterBinary(Number2GrayCode(31), 8))
    Log(FormatterBinary(Number2BinaryCode(31), 8))
   
    Log(FormatterBinary(Number2GrayCode(31), 16))
    Log(FormatterBinary(Number2BinaryCode(31), 16))
   
End Sub

Public Sub Number2GrayCode(a As Int) As String
    Dim b As Int = Bit.Xor(Bit.Shiftright(a,1),a)
    Return Bit.ToBinaryString(b)
End Sub

Public Sub Number2BinaryCode(a As Int) As String
    Return Bit.ToBinaryString(a)
End Sub

Public Sub FormatterBinary (Value As String, Size As  Int) As String
    Dim formatter As B4XFormatter
    formatter.Initialize
    formatter.GetDefaultFormat.GroupingCharacter = ""
    formatter.GetDefaultFormat.DecimalPoint = ""
    formatter.GetDefaultFormat.IntegerPaddingChar = "0"
    formatter.GetDefaultFormat.MinimumIntegers = Size
    Return formatter.Format(Value)
End Sub
 

emexes

Expert
Licensed User
Better way:

B4X:
Sub ZeroPadLeft(S As String, L As Int) As String

    Dim sb As StringBuilder
    sb.Initialize
  
    For I = 1 To L - S.Length
        sb.Append("0")
    Next

    Return sb.Append(S).ToString
  
End Sub
 
Last edited:

emexes

Expert
Licensed User
Perhaps the fastest way using only core String functions:

B4X:
Sub ZeroPadLeft16(S As String)

    Return "0000000000000000".SubString(S.Length) & S
    
End If

Sub ZeroPadLeft8(S As String)

    Return "00000000".SubString(S.Length) & S
    
End Sub
 
Thanks to all for better/best solutions. I always like shortest/smartest way to code. It helps to keep focus on core idea of task. Thanks.
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…