This code will let you convert an arbitrary string with 0s and 1s only into a Hex value, and back.
Why?
Maybe you have a Javascript component that renders based on a long array of bits.
Lets say
var b = "101010101100101001000101011101010010011100000010100110000010001010010011000000000001000010101001110000000001100010100000"
The string can be stored in the DB as nvarchar(max) field, but then if you want to reduce the length by 1/8th, you can convert it into a Hexadecimal representation
The above would be equivalent to
27029822 930010A9C018A0
Ok, this is the 'bit packing' concept implemented in a very crude way.
Anyhow, the output is human readable and probably easier to pass in a JSON
The functions are as below
Private Function bitArrayStrtoHex(b As String) As String
Dim sb As New System.Text.StringBuilder
For i As Integer = 0 To b.Length - 1 Step 8
Dim cut8 As String
If b.Length - i <= 8 Then
cut8 = b.Substring(i).PadRight(8, "0"c)
Else
cut8 = b.Substring(i, 8)
End If
Dim miniHex As String = Convert.ToString(Convert.ToInt32(cut8, 2), 16).ToUpper
sb.Append(miniHex.PadLeft(2, "0"c))
Next
Return sb.ToString
End Function
Private Function HextobitArryStr(h As String) As String
Dim sb As New System.Text.StringBuilder
For i As Integer = 0 To h.Length - 1 Step 2
Dim bitS As String = Convert.ToString(Convert.ToInt32(h.Substring(i, 2), 16), 2).PadLeft(8, "0"c)
sb.Append(bitS)
Next
Return sb.ToString
End Function
Why?
Maybe you have a Javascript component that renders based on a long array of bits.
Lets say
var b = "101010101100101001000101011101010010011100000010100110000010001010010011000000000001000010101001110000000001100010100000"
The string can be stored in the DB as nvarchar(max) field, but then if you want to reduce the length by 1/8th, you can convert it into a Hexadecimal representation
The above would be equivalent to
27029822 930010A9C018A0
Ok, this is the 'bit packing' concept implemented in a very crude way.
Anyhow, the output is human readable and probably easier to pass in a JSON
The functions are as below
Private Function bitArrayStrtoHex(b As String) As String
Dim sb As New System.Text.StringBuilder
For i As Integer = 0 To b.Length - 1 Step 8
Dim cut8 As String
If b.Length - i <= 8 Then
cut8 = b.Substring(i).PadRight(8, "0"c)
Else
cut8 = b.Substring(i, 8)
End If
Dim miniHex As String = Convert.ToString(Convert.ToInt32(cut8, 2), 16).ToUpper
sb.Append(miniHex.PadLeft(2, "0"c))
Next
Return sb.ToString
End Function
Private Function HextobitArryStr(h As String) As String
Dim sb As New System.Text.StringBuilder
For i As Integer = 0 To h.Length - 1 Step 2
Dim bitS As String = Convert.ToString(Convert.ToInt32(h.Substring(i, 2), 16), 2).PadLeft(8, "0"c)
sb.Append(bitS)
Next
Return sb.ToString
End Function
Comments
Post a Comment