Home All Groups Group Topic Archive Search About

need convert a value (integer) into bytearray with bits 0-31

Author
26 Nov 2006 11:00 PM
SSPoke
Hello
I attempted to make one in VB.NET
but it dind't work at all..

Private buffer() As Byte 'OUTPUT OF BITS goes here
Dim bitPosition as Integer = Buffer(i) * 8 'current position of Buffer
Private bitMaskOut() As Integer = {0, 1, 3, 7, 15, 31, 63, 127, 255,
511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, &H1FFFF, &H3FFFF,
&H7FFFF, &HFFFFF, &H1FFFFF, &H3FFFFF, &H7FFFFF, &HFFFFFF, &H1FFFFFF,
&H3FFFFFF, &H7FFFFFF, &HFFFFFFF, &H1FFFFFFF, &H3FFFFFFF, &H7FFFFFFF,
-1}

    Sub setBits(ByVal numBits As Integer, ByVal value As Integer)
        Dim bytePos As Integer = bitPosition >> 3
        Dim bitOffset As Integer = 8 - (bitPosition And 7)
        bitPosition += numBits

        While numBits > bitOffset
        '    buffer(bytePos) &= ~ bitMaskOut(bitOffset)        'mask out the
desired area
        Buffer(bytePos) = -(Buffer(bytePos) And bitMaskOut(bitOffset))
- 1
        '    buffer(bytePos) |= (value >> (numBits-bitOffset)) and
bitMaskOut(bitOffset)
        Buffer(bytePos) = (Buffer(bytePos) Or (value >> (numBits -
bitOffset)) And bitMaskOut(bitOffset))
        bytePos += 1
        numBits -= bitOffset
        End While
        If (numBits = bitOffset) Then
        '    buffer(bytePos) &= ~ bitMaskOut(bitOffset)
        Buffer(bytePos) = -(Buffer(bytePos) And bitMaskOut(bitOffset) -
1)

        '    buffer(bytePos) |= value and bitMaskOut(bitOffset)
        Buffer(bytePos) = (Buffer(bytePos) Or value And
bitMaskOut(bitOffset))
        Else
        '    buffer(bytePos) &= ~ (bitMaskOut(numBits)<<(bitOffset -
numBits))
        Buffer(bytePos) = -(Buffer(bytePos) And (bitMaskOut(numBits) <<
(bitOffset - numBits)) - 1)
        '    buffer(bytePos) |= (value and bitMaskOut(numBits)) <<
(bitOffset - numBits)
        Buffer(bytePos) = (Buffer(bytePos) Or (value And
bitMaskOut(numBits)) << (bitOffset - numBits))
        End If
    End Sub

could someone tell me why it doesn't work? or better yet is there a
built in function to do this much quicker? I kinda seen BitArrays
inside vb.net 2005

Any help would be appericated thanks

Author
27 Nov 2006 11:25 AM
Robinson
Not sure what your intention is here.  Are you wanting to create a single
byte for each of the bits in an integer that contains the value either 0 or
1?  If that is your intention, there are a couple of ways of doing it.  Here
is just one way:


Public Sub ToArray(ByVal theValue As Integer, ByVal theArray() As Byte)

    If theArray.Length <> 32 Then
        Throw New ArgumentException("theArray must be 32 bytes in length")
    End If

    For i As Integer = 0 To 31

        theArray(i) = theValue And 1
        theValue = theValue >> 1

    Next

End Sub