gpt4 book ai didi

c# - 从 Java 中的字节获取 int,首先在 C# 中编码

转载 作者:搜寻专家 更新时间:2023-11-01 09:08:23 25 4
gpt4 key购买 nike

我在从首先用 C# 编码的字节数组转换 int 时遇到问题。我首先将它转换为 big-endian,因为 Java 在 big-edian 而不是 small 中工作。下面的代码将into编码成字节

    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 将两个数组附加在一起。这是有效的,因为我在 C# 和 C# 之间使用过它。欢迎消息首先加载一个头字节,让客户端知道信息是什么。当我尝试对其进行解码时,我在 Java 端得到了奇怪的值。我不确定我是否解码或编码不正确。 java端就是这样。这是在 Android 设备上运行的:

   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可以配置为使用 order() 将多字节值解码为大端或小端方法。

例如:

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

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

关于c# - 从 Java 中的字节获取 int,首先在 C# 中编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10159713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com