【问题标题】:Obtain low and high order nybbles from byte within Java ByteBuffer从 Java ByteBuffer 中的字节获取低位和高位 nybbles
【发布时间】:2012-03-18 04:13:07
【问题描述】:

我需要从 ByteBuffer 中存储的字节中提取两个整数值(小端序)

ByteBuffer bb = ByteBuffer.wrap(inputBuffer);
bb.order(ByteOrder.LITTLE_ENDIAN);

我需要从 ByteBuffer 中的任何字节获取的值是:

长度 = 低位半字节的整数值

频率 = 高位半字节的整数值

目前我正在使用此代码提取低阶 nybble:

length = bb.getInt(index) & 0xf;

这似乎工作得很好。然而,我似乎无法正确解释高阶 nybble。

我对位移或掩码感到有些困惑,我认为我需要执行此操作,任何建议都会非常有帮助。

非常感谢!!

【问题讨论】:

  • 请发布您尝试过的代码并准确描述它的问题所在。

标签: java byte mask bytebuffer bit-shift


【解决方案1】:

我需要从一个字节中提取两个整数值

所以你需要得到一个字节而不是一个int,字节顺序无关紧要。

int lowNibble = bb.get(index) & 0x0f; // the lowest 4 bits
int hiNibble = (bb.get(index) >> 4) & 0x0f; // the highest 4 bits.

【讨论】:

  • 谢谢彼得,只是票!!
【解决方案2】:

要获得高位半字节,您需要做的就是位移;低位将简单地脱落。

int val = 0xAB;
int lo = val & 0xF;
int hi = val >> 4;
System.out.println("hi is " + Integer.toString(hi, 16));
System.out.println("lo is " + Integer.toString(lo, 16));

【讨论】:

  • 看看int val = (byte) 0xAB;会发生什么;)
猜你喜欢
  • 1970-01-01
  • 2010-10-15
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 2011-07-15
  • 2020-09-07
  • 2011-02-02
  • 1970-01-01
相关资源
最近更新 更多