将16位布尔数组转换为整数

时间:2015-02-08 20:11:06

标签: arrays vb.net

我已经找到了如何做到与将整数转换为16位布尔数组相反的方法。

 Dim ND1_Array As New System.Collections.BitArray(System.BitConverter.GetBytes(Data(2)))

我试过这个

Dim barray(15) As Boolean : barray(0) = True : barray(2) = True : barray(4) = True
    Dim bittoint As Integer
    bittoint = Convert.ToInt32(barray(0), 0)

此代码会抛出错误吗? 我已经看过网络,但找不到如何做到这一点。

bittoint = BitConverter.ToInt32(barray(0), 0)

这也有错误 错误1“布尔”类型的值无法转换为“字节的1维数组”。 C:\ PLC \ TCPClientClean \ TCPClientClean \ ChatClient.vb 201 41 TCPClientClean

这就是我想出的。不确定什么是更好的方法?我刚看到提供的新更新代码。

Dim BoolStg As String
    Dim BoolArra1DexBit As Boolean
    Dim BitArray1ToInt16 As Integer
    For BarryDex = 0 To 15
        BoolArra1DexBit = BoolAray1(BarryDex)
        If BoolArra1DexBit = True Then
            BoolStg = "1" & BoolStg
        Else : BoolStg = "0" & BoolStg
        End If
    Next
    BitArray1ToInt16 = Convert.ToInt16(BoolStg, 2)

2 个答案:

答案 0 :(得分:1)

小例子

    Dim myFlags As Integer = &H11
    MsgBox(Convert.ToString(myFlags, 2))

    Dim ND1_Array As New System.Collections.BitArray(System.BitConverter.GetBytes(myFlags))

    Dim myFlags_tmparray(0) As Integer
    ND1_Array.CopyTo(myFlags_tmparray, 0)

    MsgBox(Convert.ToString(myFlags_tmparray(0), 2))

答案 1 :(得分:0)

这是一个扩展方法,它将返回整数等效的小端或大端,并允许您切换TwosComplement:

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim barray(15) As Boolean : barray(0) = True : barray(2) = True : barray(4) = True

        Dim BigEndianInteger As Integer = barray.ToInteger(False)
        Dim LittleEndianInteger As Integer = barray.ToInteger() ' <-- default is Little Endian with TwosComplement turned On

        Debug.Print("BigEndianInteger = " & BigEndianInteger)
        Debug.Print("LittleEndianInteger = " & LittleEndianInteger)
    End Sub

End Class

Public Module Extensions

    <Runtime.CompilerServices.Extension()> _
    Public Function ToInteger(ByVal BooleanArray() As Boolean, Optional ByVal LittleEndian As Boolean = True, Optional ByVal TwosComplement As Boolean = True) As Integer
        If BooleanArray.Length <= 32 Then
            Dim sum As Integer
            Dim values As New List(Of Boolean)(BooleanArray)
            If Not LittleEndian Then
                values.Reverse()
            End If
            For i As Integer = 0 To values.Count - 1
                If values(i) Then
                    If i < (values.Count - 1) Then
                        sum = sum + Math.Pow(2, i)
                    ElseIf TwosComplement Then
                        sum = sum - Math.Pow(2, i)
                    Else
                        sum = sum + Math.Pow(2, i)
                    End If
                End If
            Next
            Return sum
        Else
            Throw New Exception("Boolean array length must be less than or equal to 32.")
        End If
    End Function

End Module