Charles Y. Charles Y. - 2 months ago 11
Vb.net Question

Storing 4 bits from a byte in VB.NET

What is the best way to store 4 bits from a byte in VB.NET? Where best means:


  • The most straightforward method of storage from a Byte type.

  • The easiest to work with while performing bitwise operations.

  • Straightforward conversion of the bits to other types.



Storing them in a BitArray via its constructor reverses the order of the bits. This means that attempting to get the value of the first bit will require looking for that value in the last entry in the BitArray.
Storing them in an Array of Booleans does no present a straightforward way of conversion from the byte, and impedes the conversion to other types.

Answer

You could always create your own custom class if you don't like how BitArray works:

Public Class MaskedByte

    Private innerValue As Byte
    Private mask As Byte

    Public Sub New()
        MyBase.New
    End Sub

    Public Sub New(ByVal value As Byte, ByVal mask As Byte)
        MyBase.New
        innerValue = value
        Mask = mask
    End Sub

    Public Property Value As Byte
        Get
            Return (innerValue And Mask)
        End Get
        Set
            innerValue = value
        End Set
    End Property

    Public Property Mask As Byte
        Get
            Return mask
        End Get
        Set
            mask = value
        End Set
    End Property

End Class

Then, to use:

Dim myMaskedByte As MaskedByte
myMaskedByte.Mask = &HF0
myMaskedBytef3.Value = someValue

(I don't know VB.NET, but I think this is correct).

Comments