标签:
import java.nio.ByteBuffer; public class Program { public static void main(String[] args) { ByteBuffer buf = ByteBuffer.allocate(3); writeInt24(-113, buf); buf.flip(); int i1 = readInt24(buf); buf.clear(); writeInt24(9408399, buf); buf.flip(); int i2 = readUnsigedInt24(buf);//readInt24(buf); System.out.println("i1 = " + i1); System.out.println("i2 = " + i2); } static void writeInt24(int val, ByteBuffer buf) { buf.put((byte)(val >> 16)); buf.put((byte)(val >> 8)); buf.put((byte)val); } static int readInt24(ByteBuffer buf) { byte[] data = new byte[3]; for (int i = 0; i < 3; ++i) data[i] = buf.get(); return (data[0] << 16) | (data[1] << 8 & 0xFF00) | (data[2] & 0xFF);// Java总是把byte当做有符号处理;我们可以通过将其和0xFF进行二进制与来得到有符号的整型 } static int readUnsigedInt24(ByteBuffer buf) { byte[] data = new byte[3]; for (int i = 0; i < 3; ++i) data[i] = buf.get(); return (data[0] << 16 & 0xFF0000) | (data[1] << 8 & 0xFF00) | (data[0] & 0xFF); } }
标签:
原文地址:http://www.cnblogs.com/codingthings/p/4585434.html