问题
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.
回答1:
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();
...
回答2:
Maybe the BitConverter class can be of assistance. Have a look here.
来源:https://stackoverflow.com/questions/10159713/get-int-from-bytes-in-java-encoded-first-in-c-sharp