将整数转换为字节数组 VB.net
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23319726/
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
Convert integers to a Byte array VB.net
提问by vishva8kumara
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 中编写相同的代码 我在 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.
谢谢你。
回答by Bj?rn-Roger Kringsj?
You can convert an integer (32 bit (4 byte))to a byte array using the BitConverterclass.
您可以使用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
回答by Wizard
''' <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

