0

好的,我需要从 3.268.760 位长的数据表中存储/检索一点。

Using w As New BinaryWriter(File.Open("test.bin", FileMode.Create))
    for x = 1 to 3268760
        For i = 1 To 3268760
            w.Write(countBits(bitLikeness(u(i), u(x))) > 10)
        Next
     Next
End Using

存储一个布尔值,w.write(?)对于 false/true 值表示 0/1,但 Vb.net 似乎使用整个字节来存储这些数据,这对我的表来说太贵了(3.268.760^2)

有没有一种实用的方法可以使用 vb.net 从文件中存储/检索单个位?(意味着尽可能少地转换为其他类型)。

4

1 回答 1

1

包装 BinaryReader/Writer 可能是您最好的选择。

Public Class BitWriter

    Private ReadOnly mBinaryWriter As BinaryWriter

    Private mBuffer As Integer
    Private mBufferCount As Integer

    Public Sub New(binaryWriter As BinaryWriter)
        mBinaryWriter = binaryWriter
    End Sub

    Public Sub WriteBit(bit As Boolean)

        If mBufferCount = 32 Then

            mBinaryWriter.Write(mBuffer)

            mBuffer = 0
            mBufferCount = 0

        End If

        If bit Then mBuffer = mBuffer Or (1 << mBufferCount)

        mBufferCount += 1

    End Sub

    Public Sub Flush()

        mBinaryWriter.Write(mBuffer)

        mBuffer = 0
        mBufferCount = 0

    End Sub

End Class

并读回这些位

Public Class BitReader

    Private ReadOnly mBinaryReader As BinaryReader

    Private mBuffer As Integer
    Private mBufferCount As Integer

    Public Sub New(binaryReader As BinaryReader)
        mBinaryReader = binaryReader
        mBuffer = -1
    End Sub

    Public Function ReadBit() As Boolean

        If mBuffer = -1 OrElse mBufferCount = 8 Then

            mBuffer = mBinaryReader.ReadInt32()
            mBufferCount = 0

        End If

        Dim toReturn As Boolean = ((mBuffer >> mBufferCount) And 1) = 1

        mBufferCount += 1

        Return toReturn

    End Function

End Class
于 2012-04-11T08:59:03.167 回答