0
0

More than 1 year has passed since last update.

ByteBuffer#getInt()でBufferUnderflowExceptionが出るときの対処法

Last updated at Posted at 2022-09-30

2byteの16進数を整数にしたい

Jpegのメタデータのセグメント長を取得したかったのですが、思いもしなかったところでハマりました。

byte[] bytes = new byte[]{(byte)0x03,(byte)0x1e} // これから798を求めたい
ByteBuffer.wrap(bytes).getInt(); //BufferUnderflowExceptionが発生

javaのIntは32bitの符号付き整数

つまりbyte[4]です。

上のコードではbyte[2]です。ByteBuffer#getInt()は4byte取得しよとします。僕はここで自動で0x00で埋めてくれると勝手に思ってました。

getShort()を使う

ByteBuffer#getShort()はshort型なので2byteです。これで動きます。

4byteになるまで埋める

これが最適解かはわかりませんがとりあえず動きます。
3byteのときはこの方法が良いと思います。

byte[] tmp = new byte[4]{0x00,bytes[0],bytes[1],bytes[2]} // 今回は符号を考慮しないのでゼロで埋める。
Bytebuffer.wrap(tmp).getInt(); // 798
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0