将整数转换为字节数组VB.net。

时间:2022-12-31 21:09:34

I have the following Java code working as expected, to convert some numbers to an array of Bytes before writing to a stream.

我有如下的Java代码按照预期工作,在写入流之前将一些数字转换成字节数组。

byte[] var1 = new byte[]{
    (byte)-95,
    (byte)(240 / 256 / 256 % 256),
    (byte)(240 / 256 % 256),
    (byte)(240 % 256),
    (byte)0
};

I need to write the same in VB .net I tried the following code in VB .net, but no success.

我需要在VB。net中编写同样的代码。

Dim var1(4) As Byte
    var1(0) = Byte.Parse(-95)
    var1(1) = Byte.Parse(240 / 256 / 256 Mod 256)
    var1(2) = Byte.Parse(240 / 256 Mod 256)
    var1(3) = Byte.Parse(240 Mod 256)
    var1(4) = Byte.Parse(0)

Am I doing it wrong.? How to get it done properly..

我做错了吗?如何把它做好

Thank you.

谢谢你!

1 个解决方案

#1


4  

You can convert an integer (32 bit (4 byte)) to a byte array using the BitConverter class.

可以使用位转换器类将整数(32位(4字节))转换为字节数组。

Dim result As Byte() = BitConverter.GetBytes(-95I)

Dim b1 As Byte = result(0) '161
Dim b2 As Byte = result(1) '255
Dim b3 As Byte = result(2) '255
Dim b4 As Byte = result(3) '255

#1


4  

You can convert an integer (32 bit (4 byte)) to a byte array using the BitConverter class.

可以使用位转换器类将整数(32位(4字节))转换为字节数组。

Dim result As Byte() = BitConverter.GetBytes(-95I)

Dim b1 As Byte = result(0) '161
Dim b2 As Byte = result(1) '255
Dim b3 As Byte = result(2) '255
Dim b4 As Byte = result(3) '255