在VB.NET中从一个字节存储4位的最佳方法是什么?最好的意思是:
通过其构造函数将它们存储在BitArray中会反转位的顺序。这意味着尝试获取第一位的值将需要在BitArray的最后一个条目中查找该值。 将它们存储在布尔数组中并不能提供从字节转换的简单方法,并阻碍转换为其他类型。
答案 0 :(得分:1)
如果您不喜欢BitArray
的工作原理,您可以随时创建自己的自定义类:
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
然后,使用:
Dim myMaskedByte As MaskedByte
myMaskedByte.Mask = &HF0
myMaskedBytef3.Value = someValue
(我不知道VB.NET,但我认为这是正确的。)
答案 1 :(得分:0)
将其保留在字节中:
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
清除这些位也非常简单:
Dim value As Byte = (oldValue And &HF0)
如果你想保持最低价,你只需反转十六进制值:
Dim value As Byte = (oldValue And &H0F)
答案 2 :(得分:0)
我同意将它们保留在一个字节中,但不清楚为什么???你想要一个半字节......这个例子将一个字节的半字节放入不同的数组
'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