Question

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.

Was it helpful?

Solution

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

OTHER TIPS

I agree with keeping them in a byte, however it is not clear why??? you want one of the nibbles... This example puts both nibbles of a byte into different arrays

'Test Data
'create a byte array containing EVERY possible byte value
Dim b(255) As Byte
For x As Integer = 0 To b.Length - 1
    b(x) = CByte(x)
Next

Dim bMS(255) As Byte 'most sig.
Dim bLS(255) As Byte 'least sig.
Const mask As Byte = 15
'
For x As Integer = 0 To b.Length - 1
    bMS(x) = b(x) >> 4
    bLS(x) = b(x) And mask
Next

Keep it in the byte:

Dim b1 As Boolean = (value And &H01) = 1
Dim b2 As Boolean = (value And &H02) = 1
Dim b3 As Boolean = (value And &H04) = 1
Dim b4 As Boolean = (value And &H08) = 1

Clearing the bits is also really simple:

Dim value As Byte = (oldValue And &HF0)

If you want to keep the least significant you simply reverse the hex value:

Dim value As Byte = (oldValue And &H0F)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top