为了账号安全,请及时绑定邮箱和手机立即绑定

在 Scala 中将 Int32 表示为 4 个字节

在 Scala 中将 Int32 表示为 4 个字节

撒科打诨 2023-04-13 16:56:52
我正在做一个二进制协议解析,我试图从字节数组中读取一个字符串。在这个字节数组中,前 4 个字节表示字符串的长度。String 的长度表示为 Int32。例如,这里是字节数组:val arr = "45 0 0 0 65 59 78 76 89 89 78 67 56 67 78 89 98 56 67 78 89 90 98 56 67 78 89 90 56 67 78 89 90 56 67 78 89 90 56 67 78 89 90 56 67 78 89 56 67"从上面的数组可以看出,前 4 个字节45 0 0 0表示后面的 String 的大小,在本例中为 45 个字节长。我知道 Int32 需要 4 个字节才能在 JVM 上表示。但我不明白如何解析前 4 个字节并推断出以下字符串的大小在上面的示例中将为 45!所以我基本上需要的是可以将数组转换45 0 0 0为 45 的东西!我说的有道理吗?有什么建议吗?res60: Array[Byte] = Array(45, 0, 0, 0)scala> ByteBuffer.wrap(res60).getInt()res61: Int = 754974720res61 不是我所期待的!
查看完整描述

2 回答

?
婷婷同学_

TA贡献1844条经验 获得超8个赞

ByteBuffer默认情况下具有大端字节顺序,但您的 int 使用小端字节顺序。您必须明确地将 ByteBuffer 转换为小端,例如:


byte[] input = { 45, 0,  0,  0 };

ByteBuffer bb = ByteBuffer.wrap(input).order(ByteOrder.LITTLE_ENDIAN); // <---    

int length = bb.getInt();

System.out.println(length); // 45


查看完整回答
反对 回复 2023-04-13
?
慕雪6442864

TA贡献1812条经验 获得超5个赞

你可以这样做(Java):


String input = "45 0 0 0 65 59 78 76 89 89 78 67 56 67 78 89 98 56 67 78 89 90 98 56 67 78 89 90 56 67 78 89 90 56 67 78 89 90 56 67 78 89 90 56 67 78 89 56 67";


String[] arr = input.split(" ");

int i = 0;

int len = Integer.parseInt(arr[i++]) +

          256 * (Integer.parseInt(arr[i++]) +

                 256 * (Integer.parseInt(arr[i++]) +

                        256 * Integer.parseInt(arr[i++])));

char[] buf = new char[len];

for (int j = 0; j < len; j++)

    buf[j] = (char) Integer.parseInt(arr[i++]);

String result = new String(buf);


System.out.println(result);

输出


A;NLYYNC8CNYb8CNYZb8CNYZ8CNYZ8CNYZ8CNYZ8CNY8C


查看完整回答
反对 回复 2023-04-13
  • 2 回答
  • 0 关注
  • 132 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信