首先从Java中的字节INT,连接codeD在C# [英] Get int from bytes in Java, encoded first in C#

查看:102
本文介绍了首先从Java中的字节INT,连接codeD在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,从字节数组转换为int首先连接在C#codeD。我首先将它转换为大端因为Java工作在大edian,而不是小的。下面code EN codeS中的成成字节

  Console.WriteLine(新的数据客户端已连接!);
    字节[] = welcomeMessage ASCIIEncoding.ASCII.GetBytes(欢迎小伙子,请让我知道你需要什么!);    welcomeMessage = Byte.add(BitConverter.GetBytes(System.Net.IPAddress.HostToNetworkOrder(20)),welcomeMessage);

Byte.add两个数组附加在一起。这工作,因为我有C#之间使用它为C#。欢迎消息首先被装入一个头字节,让客户知道的信息是什么。我得到在Java端奇怪的价值观,当我尝试去code吧。我不知道如果我解码或编码不正确。 Java端就是这样。这是一个Android设备上运行:

 如果(ByteBuffer.wrap(缓冲).getInt()== 20)
   {
          latestMessage =新的String(缓冲);
   }
   latestMessage =将String.valueOf(ByteBuffer.wrap(缓冲液).getInt(0)); //让我看看这是什么样的价值。斜面连接调试出于某种原因自动柜员机。


解决方案

一个的的ByteBuffer 可以配置为使用脱code多字节的值都用大或小尾数的<一个href=\"http://docs.oracle.com/javase/6/docs/api/java/nio/ByteBuffer.html#order%28java.nio.ByteOrder%29\"相对=nofollow> 为了() 方法。

例如:

 最后的ByteBuffer BB = ByteBuffer.wrap(缓冲);
bb.order(ByteOrder.LITTLE_ENDIAN);最终诠释我= bb.getInt();
...

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.

解决方案

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();
...

这篇关于首先从Java中的字节INT,连接codeD在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆