You can use the BitConverter
class:
Dim bytes As Byte() = BitConverter.GetBytes(byte_val1)
Now bytes(0)
contains the lower byte (00000011) and bytes(1)
contains the higher byte (00000000).
سؤال
I have a 16-bit value like this:
0000000000000011
I want to split this in two 8-bit values like:
00000000 and 00000011
The 16-bit value is a variable, byte_val1
, which is a unsigned 16-bit integer.
How can I do this in VB.NET?
المحلول
You can use the BitConverter
class:
Dim bytes As Byte() = BitConverter.GetBytes(byte_val1)
Now bytes(0)
contains the lower byte (00000011) and bytes(1)
contains the higher byte (00000000).
نصائح أخرى
To obtain lower 8 bits, you need to and it with 11111111
, or 0xff
To obtain upper 8 bits, you need to and it with 1111111100000000
, or 0xff00
Then to an arithmetic left shift exactly 8 bits.
I have not done Visual Basic in a while, but the idea is as follows:
word a = 1930392;
byte alower = a & 0xff;
byte ahigher = (a & 0xff00) >> 8;
Oh, here's a code I made with three textboxes named a
, alower
, aupper
and a button btnDoIt
:
Private Sub btnDoIt_Click(sender As Object, e As EventArgs) Handles btnDoIt.Click
Dim localA = Integer.Parse(a.Text())
Dim localALower = localA And &HFF
Dim localAUpper = (localA And &HFF00) >> 8
alower.Text = localALower
aupper.Text = localAUpper
End Sub
Sidenote: (localA And &HFF00) >> 8
is equivelent to (localA >> 8) And &HFF
A simple bitshift should work if you want certain byte(s) from any value (32 bit, 64 bit, 128 bit, etc..).
The simplest way is to AND
("binary AND", also written as "&") the source with the bits you want and then to shift it as many times as needed to get the desired value.
Dim initial as Integer = &H123456 ' Hex: 0x123456
Dim result as Byte = (initial AND &H00FF00) >> 8
'result = 0x34
and if you would like to join them again it's even simpler:
Dim initial as Integer = &H123456 ' Hex: 0x123456
Dim result_a as Byte = (initial AND &H00FF00) >> 8
Dim result_b as Byte = (initial AND &HFF0000) >> 16
Dim final as Integer = (result_a << 8) or (result_b << 16)
'final = 0x123400