我正在尝试将布尔数组转换为字节。
例如:
Dim boolarray1() As Boolean = {True, True, True, False, False, False, False, False}
我一直在尝试将此值转换为另一个名为vOUT
的变量作为字节。在这种情况下,vOUT
应该给我一个值7。
任何帮助将不胜感激。
答案 0 :(得分:2)
使用带左移和/或运算符的位,
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
答案 1 :(得分:1)
根据您的示例,如果数组的最后一个元素是MSB或最高位,那么您可以使用它:
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)
结果将保持&#39; 7&#39;对于给定的boolarray1。如果您需要第一个索引中的MSB,那么只需删除行:temp = StrReverse(temp)
答案 2 :(得分:0)
我就是这样做的:
Public Function convertToByte(bits() As BitArray) As Byte Dim bytes(0) As Byte bits.CopyTo(bytes, 0) Return (bytes(0)) End Function