Reputation: 1
I'm trying to convert boolean array to byte.
For example:
Dim boolarray1() As Boolean = {True, True, True, False, False, False, False, False}
I've been trying to convert this value to another variable called vOUT
as byte. In this case vOUT
should give me an value 7.
Any help will be appreciated.
Upvotes: 0
Views: 1909
Reputation: 51
This is how I would do it:
Public Function convertToByte(bits() As BitArray) As Byte Dim bytes(0) As Byte bits.CopyTo(bytes, 0) Return (bytes(0)) End Function
Upvotes: 0
Reputation: 11773
Using bits with left shift and or operators,
Dim boolarray1() As Boolean = {True, True, True, False, False, False, False, False}
Dim vout As Byte = 0
Dim bytPos As Integer = 0 ' to change order make this 7
For Each b As Boolean In boolarray1
If b Then
vout = vout Or CByte(1 << bytPos)
End If
bytPos += 1 ' to change order make this -=
Next
Upvotes: 2
Reputation: 262
Based from your example, if the last element of the array is the MSB or the most significant bit, then you can use this:
Dim boolarray1() As Boolean = {True, True, True, False, False, False, False, False}
Dim temp As String = ""
For i As Integer = 0 To boolarray1.Length - 1
If boolarray1(i) Then
temp &= "1"
Else
temp &= "0"
End If
Next
temp = StrReverse(temp)
Dim result As Byte = Convert.ToByte(temp, 2)
result will hold '7' for the given boolarray1. If you need the MSB in the first index, then just remove the line: temp = StrReverse(temp)
Upvotes: 1