Is it possible store/retrieve bit data from file using VB.Net BinaryWriter?
-
30-05-2021 - |
Domanda
Ok, I need to store/retrieve a bit from a data table of 3.268.760 bits long.
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
the w.write(?)
stores a boolean value meaning 0/1 for false/true values, but Vb.net seems to use an whole byte to store this data which is too expensive for my table (3.268.760^2)
Is there a pratical way to store/retrive single bits from a file using vb.net? (meaning as little as possible conversion to other types).
Soluzione
Wrapping the BinaryReader/Writer is probably your best option.
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
And to read the bits back
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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow