Convert integers to a Byte array VB.net

折月煮酒 提交于 2019-12-10 10:17:39

问题


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

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.

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:


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

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



回答2:


''' <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>
Public Overloads Shared Sub GetBytes(Int As Integer, ByRef DestinationBuffer As Byte(), DestinationOffset As Integer)
    DestinationBuffer(DestinationOffset + 0) = CByte(Int And &HFF)
    DestinationBuffer(DestinationOffset + 1) = CByte(Int >> 8 And &HFF)
    DestinationBuffer(DestinationOffset + 2) = CByte(Int >> 16 And &HFF)
    DestinationBuffer(DestinationOffset + 3) = CByte(Int >> 24 And &HFF)
End Sub


来源:https://stackoverflow.com/questions/23319726/convert-integers-to-a-byte-array-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!