好的,我需要从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(?)
存储一个布尔值,意味着0/1表示false / true值,但是Vb.net似乎使用整个字节来存储这个数据,这对我的表来说太贵了(3.268.760 ^ 2 )
使用vb.net存储/检索文件中的单个位是否有实用的方法? (意思是尽可能少地转换为其他类型)。
答案 0 :(得分: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