Java : DataInputStream replacement for endianness

五迷三道 提交于 2019-11-28 10:04:43

readBoolean() reads a single byte. readLine() reads single bytes and converts each to a char.

readUTF() reads modified UTF-8 (which has a code unit size of one octet). UTF-8 has no endianness.

There are no endianness concerns with these methods.

As to the design, consider whether the type needs to be an InputStream and whether the ByteBuffer might be useful. If you weren't using features like mark/reset and Closeable you might not expose the new type:

public class Bytes {
  public static DataInput littleEndian(final DataInput decorated) {
    class LittleInput implements DataInput {
      private ByteBuffer buffer = ByteBuffer.allocate(8);

      public int readInt() throws IOException {
        buffer.clear();
        buffer.order(ByteOrder.BIG_ENDIAN)
            .putInt(decorated.readInt())
            .flip();
        return buffer.order(ByteOrder.LITTLE_ENDIAN)
            .getInt();
      }

      //TODO: other methods    
    }

    return new LittleInput();
  }

}

I note that the popular Guava library already has LittleEndianDataInputStream.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!