How to convert a BitArray of length 8 into a single byte
-
We're working with a byte variable and i am using it like a bitfield. To do this, i use BitArray class to avoid logical operations like and, or,... My problem is when i want to reverse the operation. Starting from my BitArray object of size 8, is possible to convert to a single byte ? Thanks.
-
We're working with a byte variable and i am using it like a bitfield. To do this, i use BitArray class to avoid logical operations like and, or,... My problem is when i want to reverse the operation. Starting from my BitArray object of size 8, is possible to convert to a single byte ? Thanks.
-
We're working with a byte variable and i am using it like a bitfield. To do this, i use BitArray class to avoid logical operations like and, or,... My problem is when i want to reverse the operation. Starting from my BitArray object of size 8, is possible to convert to a single byte ? Thanks.
The BitArray class doesn't support conversions to other types (EDIT: I completely forgot about CopyTo!!). If you're only using 8 bits, you're much better off just using a Byte and doing the bit manipulation yourself. It's easy to write your own methods to automate some of this, like setting or resetting a bit. A quick little whip up:
Public Shared Function SetBit(ByVal value As Byte, ByVal position As Integer) As Byte
If position < 1 Or position > 8 Then
Throw New ArgumentOutOfRangeException("Position must be between 1 and 8.")
End IfDim mask As Byte = CByte(2 ^ (position - 1)) If Not value And mask Then value = value Or mask End If Return value
End Function
-- modified at 13:06 Wednesday 2nd May, 2007
Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
2006, 2007