如何在 VB.NET 中将 16 位值拆分为两个 8 位值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15110586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:33:17  来源:igfitidea点击:

How do I split a 16-bit value into two 8-bit values in VB.NET?

vb.net16-bit8-bit

提问by Arindam Das

I have a 16-bit value like this:

我有一个像这样的 16 位值:

 0000000000000011

I want to split this in two 8-bit values like:

我想将其拆分为两个 8 位值,例如:

 00000000    and    00000011

The 16-bit value is a variable, byte_val1, which is a unsigned 16-bit integer.

16 位值是一个变量byte_val1,它是一个无符号的 16 位整数。

How can I do this in VB.NET?

我怎样才能在 VB.NET 中做到这一点?

回答by Guffa

You can use the BitConverterclass:

您可以使用BitConverter该类:

Dim bytes As Byte() = BitConverter.GetBytes(byte_val1)

Now bytes(0)contains the lower byte (00000011) and bytes(1)contains the higher byte (00000000).

现在bytes(0)包含低字节 (00000011) 和bytes(1)高字节 (00000000)。

回答by Dmitry

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.

要获得低 8 位,您需要使用 和它11111111,或者0xff
要获得高 8 位,您需要使用1111111100000000,或者0xff00
然后进行算术左移正好 8 位。

I have not done Visual Basic in a while, but the idea is as follows:

好久没做Visual Basic了,思路如下:

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, aupperand a button btnDoIt:

哦,这里是有三个文本框命名做了我的代码aaloweraupper和一个按钮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) >> 8is equivelent to (localA >> 8) And &HFF

旁注:(localA And &HFF00) >> 8相当于(localA >> 8) And &HFF

回答by Arindam Das

A simple bitshift should work if you want certain byte(s) from any value (32 bit, 64 bit, 128 bit, etc..).

如果您想要来自任何值(32 位、64 位、128 位等)的某些字节,一个简单的位移应该可以工作。

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.

最简单的方法是AND(“二进制与”,也写为“&”)带有您想要的位的源,然后根据需要将其移位多次以获得所需的值。

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