Java byte[] to VB.NET byte[], part deux

Following on from the prior post, there are other options for converting an array of Java bytes to an array of .NET bytes. One is to do the signed-to-unsigned conversion on the Java side. Like this:

    public static String asHex (byte buf[])


        StringBuffer strbuf = new StringBuffer(buf.length * 2);

        int i;

        for (i = 0; i < buf.length; i++)


            if (((int) buf[i] & 0xff) < 0x10)


            strbuf.append(Long.toString((int) buf[i] & 0xff, 16));


        return strbuf.toString();


For an array like this:

byte[] b= { -24, 23, -40, 41, 56, -2, 11, 77, 52, -13 };

That would generate a string like this:


Then the VB conversion for that would look like this:

  Private Shared Function GetByteArray(data as System.String) as System.Byte()

    Dim b(data.Length/2-1) as System.Byte

    For i As Integer = 0 To data.Length-1 Step 2

      b(i/2)= System.Byte.Parse(data.Substring(i,2).ToUpper(), System.Globalization.NumberStyles.HexNumber )


    Return b

  End Function

To verify that it's really working, you can convert the resulting array of VB.NET bytes to an array of sbyte, and compare it with the original in the Java app. Like this:

  Private Shared Function ArrayOfByteToArrayOfSbyte(b() as System.Byte) as System.Sbyte()

    Dim sb(b.Length-1) As System.Sbyte

    Dim sb1 as System.Sbyte

    For i As Integer = 0 To b.Length-1

      if (b(i) <= 127) then

        sb1 = System.Convert.ToSbyte(b(i))


        sb1 =System.Convert.ToSbyte( b(i)- 256 )

      end if

      sb(i)= sb1


    Return sb

  End Function


Comments (0)

Skip to main content