Java byte[] to VB.NET array of bytes


Somebody asked:



I have an application in Java which encrypts data and returns the bytes in a comma separated string, e.g (-22,24,-40,41) Now when I try to convert the same into a byte array for vb.net before decryption I get an error saying “Invalid arithmetic operation”. I figured out the reason to be incompatible data type definitions for Bytes in Java and VB .Net A byte in VB .net can store only unsigned values from 0 to 255. Can you suggest a solution?


Yes. As you noticed, the Java byte and the .NET System.Byte are not the same thing.


A Java byte is a signed quantity. The legal range is -127 to 128. The equivalent in .NET is a System.Sbyte. What you need for most of the encryption libraries is an aray of .NET System.Byte, which is an unsigned quantity, with a legal range of 0 to 255.


So what you need to do is convert each element in your string of signed bytes into a System.Sbyte, then convert that array into an array of System.Byte. I am no VB expert, but supposing you start with a string generated on the Java side like this: -24,23,-40,41,56,-2,11,77,52,-13; I think something like this VB code will work:



Public Class ConvertThis


 


  Private Shared Function ArrayOfSbyteToArrayOfByte(sb() as System.Sbyte) as System.Byte()


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


    Dim b1 as System.Byte


    Dim x as Integer


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


      x= System.Convert.ToInt16(sb(i))


      if (x >= 0 ) then


        b1 =System.Convert.ToByte( sb(i) )


      else


        b1 = System.Convert.ToByte(x+256)


      end if


      b(i)= b1


    Next


    Return b


  End Function


 


 


  Public Shared Sub Main(args() as String)


 


    Dim s as New System.String(“-24,23,-40,41,56,-2,11,77,52,-13”)


 


    Dim i as Integer


    Dim ss as System.String()


    Dim delimStr As String = ” ,”


    Dim delimiter As Char() = delimStr.ToCharArray()


    ss= s.Split(delimiter)


 


    System.Console.WriteLine()


    System.Console.WriteLine(“Original string:”)


    System.Console.WriteLine(”  {0}”, s)


 


    System.Console.WriteLine()


    System.Console.WriteLine(“As array of sbyte:”)


    Dim sb(ss.Length-1) as System.Sbyte


 


    System.Console.Write(”  “)


    For i = 0 To ss.Length-1


      sb(i)= System.Sbyte.Parse(ss(i))


      System.Console.Write(“{0:D}  “, sb(i))


    Next


 


    System.Console.WriteLine()


    System.Console.WriteLine()


    System.Console.WriteLine(“As array of byte:”)


 


    Dim b as System.Byte()


    b=ArrayOfSbyteToArrayOfByte(sb)


    System.Console.Write(”  “)


    For i = 0 To b.Length-1


      System.Console.Write(“{0:X2}  “, b(i))


    Next


    System.Console.WriteLine()


    System.Console.WriteLine()


 


  End Sub


 


End Class


-Dino

Comments (3)

  1. Tanveer Badar says:

    Signed numbers run from -n to -(-n) – 1, so signed byte would run from -128 to 127, not -127 to 128.