3

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.

2
  • 1
    What does to no avail mean? What was the error or output? Also note that Byte.Parse parses a string, not an integer, as noted in the documentation. Commented Apr 27, 2014 at 5:25
  • For "-95", it halted with an exception, that -95 is too small for Byte, and "240 / 256 / 256 Mod 256" didn't work either. Commented Apr 27, 2014 at 7:36

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

Comments

0
''' <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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.