### Int to Binary String

Various ways to convert a Number from type integer into a Binary String.
Sub using Bit Shift
' Converts a number as into a binary string
' Parameter: number to convert, length of the binary being 8 or 32 bit
' Return the nunber as a binary string
`Private Sub ToBinaryString(number As Int, length As Int) As String
length = length - 1
Dim sb As StringBuilder
sb.Initialize
Dim x As Int = Bit.ShiftLeft(1, length)
For i = 0 To length
Dim ii As Int = Bit.AND(number, x)
If ii <> 0 Then
sb.Append("1")
Else
sb.Append("0")
End If
x = Bit.UnsignedShiftRight(x, 1)
Next
Return sb.ToString
End Sub`
Example Output
ToBinaryString(127, 8) is 01111111
ToBinaryString(255, 8) is 11111111
Subroutine using API method toBinaryString from java.lang.Integer Class
Reference: http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html
' Converts a number to a binary string
' Parameter: number to convert
' Returns the number as a binary string
`Private Sub ToBinaryString2(number As Int) As String
Dim joI As JavaObject
' Init the Class
joI.InitializeStatic("java.lang.Integer")
' Run the conversion method
Return joI.RunMethod("toBinaryString", Array(number))
End Sub`
Example Output
ToBinaryString2(127) is 1111111
ToBinaryString2(128) is 10000000
Note:
Add leading blanks if output should be certain length. See next Sub ToBinaryString8.
Subroutine using API method toBinaryString with length 8
' Converts a number to a binary string with length 8
' Parameter: number to convert
`Private Sub ToBinaryString8(number As Int) As String
Dim result As String = ""
Dim joI As JavaObject
joI.InitializeStatic("java.lang.Integer")
result = joI.RunMethod("toBinaryString", Array(number))
Dim n As Int = result.Length
For i = n To 7
result = "0" & result
Next
Return result
End Sub`
Examples with Output
Log("0:" & ToBinaryString8(0))
Log("1:" & ToBinaryString8(1))
Log("10:" & ToBinaryString8(10))
Log("100:" & ToBinaryString8(100))
Log("255:" & ToBinaryString8(255))
Program started.
0:00000000
1:00000001
10:00001010
100:01100100
255:11111111
Subroutine using API method toBinaryString with length 5
' Converts a number to a binary string with length 5.
' Parameter: number to convert
`Private Sub ToBinaryString5(number As Int) As String
Dim result As String = ""
Dim joI As JavaObject
joI.InitializeStatic("java.lang.Integer")
result = joI.RunMethod("toBinaryString", Array(number))
Dim n As Int = result.Length
For i = n To 7
result = "0" & result
Next
'Skip the first 3 bits
Return result.SubString2(3, 8)
End Sub`
Examples
Log("10:" & ToBinaryString5(10))
10:01010

Changed: , Category: Bit and Bytes, File: T6C166M1223.htm, ID: 1223