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



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

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

我需要在VB.net中写同样的东西我在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)

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

谢谢。

您可以使用BitConverter类将整数(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
''' <summary>
''' Convert integer to user byte array w/o any allocations.
''' </summary>
''' <param name="int">Integer</param>
''' <param name="DestinationBuffer">Byte array. Length must be greater then 3</param>
''' <param name="DestinationOffset">Position to write in the destination array</param>
<Runtime.CompilerServices.MethodImpl(Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)>
Public Overloads Shared Sub GetBytes(Int32 As Integer, ByRef DestinationBuffer As Byte(), DestinationOffset As Integer)
    DestinationBuffer(DestinationOffset + 0) = CByte(Int32 And &HFF)
    DestinationBuffer(DestinationOffset + 1) = CByte(Int32 >> 8 And &HFF)
    DestinationBuffer(DestinationOffset + 2) = CByte(Int32 >> 16 And &HFF)
    DestinationBuffer(DestinationOffset + 3) = CByte(Int32 >> 24 And &HFF)
End Sub

相关内容

  • 没有找到相关文章

最新更新