【问题标题】:How to convert specific byte in a byte array to integer如何将字节数组中的特定字节转换为整数
【发布时间】:2019-09-15 02:53:18
【问题描述】:

我有一个场景,我需要根据给定的字符串返回一个整数值。 我将 String 散列到一个字节数组。现在由于我的 Integer 范围是 0-999 可以用 2bytes 表示,我希望使用字节数组的最后两个字节转换为 integer 。 但我没有得到正确的结果

我尝试过使用Byte buffer wrap方法,定义偏移为length-3,定义长度为2

ByteBuffer.wrap(bytes,bytes.length-3,2).getInt()

我期待一个基于数组最后两个字节的整数数据,但得到 线程“主”java.nio.BufferUnderflowException 中的异常

【问题讨论】:

  • 为什么是length-3 而不是length-2
  • 最后两个字节在length-2length-1

标签: java type-conversion integer byte


【解决方案1】:

ByteBuffer#getInt 从当前位置开始读取4 字节,但是您包装的ByteBuffer 的剩余大小(limit - position)为2,因此它会抛出BufferUnderflowException。相反,您应该使用ByteBuffer#getShort,它可以存储在int 中。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-07-11
  • 2018-11-19
  • 1970-01-01
  • 2010-12-28
  • 1970-01-01
相关资源
最近更新 更多