2

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.

2 Answers 2

3

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

Comments

0

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

1 Comment

Hey I just realized I forgot to include the line which converts the header int into bytes. I have changed it accordingly.

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.