Serguei Fedorov
Serguei Fedorov

Reputation: 7923

Get int from bytes in Java, encoded first in C#

I am having a problem converting an int from a byte array first encoded in C#. I first convert it into big-endian because Java works in big-edian rather than small. The following code encodes the into into bytes

    Console.WriteLine("A new data client has connected!");
    byte[] welcomeMessage = ASCIIEncoding.ASCII.GetBytes("Welcome young chap! Please let me know about anything you need!");

    welcomeMessage = Byte.add(BitConverter.GetBytes(System.Net.IPAddress.HostToNetworkOrder(20)), welcomeMessage);

Byte.add appends the two arrays together. This works because I have used it between C# to C#. The welcome message is first loaded with a header byte to let the client know what the information is. I get strange values on the java side when I try to decode it. I am not sure if I am decoding or encoding improperly. The java side is such. This is running on an android device:

   if (ByteBuffer.wrap(buffer).getInt() == 20)
   {
          latestMessage = new String(buffer); 
   }
   latestMessage = String.valueOf(ByteBuffer.wrap(buffer).getInt(0)); //Lets me see what value this is. Cant attach debugger for some reason ATM.

Upvotes: 2

Views: 1550

Answers (2)

Greg Kopff
Greg Kopff

Reputation: 16555

A ByteBuffer can be configured to decode multi-byte values as either big or little endian using the order() method.

For example:

final ByteBuffer bb = ByteBuffer.wrap(buffer);
bb.order(ByteOrder.LITTLE_ENDIAN);

final int i = bb.getInt();
...

Upvotes: 3

Vic
Vic

Reputation: 22041

Maybe the BitConverter class can be of assistance. Have a look here.

Upvotes: 0

Related Questions