0

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).

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Seems reasonable to me @Thomas, but how to retrive data afterwards (to a more complete answer).
I edited my answer to make it clear it contains two classes (and cleaned it up a bit)
Well your anwers is rigth but unfornatelly the number is really huge meaning that even storing that as bits it would requeire 1.336Tb. But i may find a work around...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.