Kenneth L. Calvert & Michael J. Donahoo: TCP/IP Sockets in Java - Practical Guide for Programmers(Second Edition), Chapter 3, BruteForceCoding.java要解决的问题是:对于一个整数(byte, int, short或者 long),怎么编码为二进制流以便于网络传输?接收端又应该如何解码?下面这个测试是对这个程序中对int数编码的进一步说明:
@Test public void testShift4() { int input = 100000001; byte high8bits = (byte) (input >> ((4 - 0 - 1) * Byte.SIZE)); assertEquals(high8bits, 5); byte secondHigt8bits = (byte) (input >> ((4 - 1 - 1) * Byte.SIZE)); assertEquals(secondHigt8bits, -11); byte thirdHigh8bits = (byte) (input >> ((4 - 2 - 1) * Byte.SIZE)); assertEquals(thirdHigh8bits, -31); byte low8bits = (byte) (input >> ((4 - 3 - 1) * Byte.SIZE)); assertEquals(low8bits, 1); System.out.println("input is: " + Integer.toHexString(input)); System.out .println("left 8 bits are: " + Integer.toHexString(high8bits)); System.out.println("2nd 8 bits are: " + Integer.toHexString(secondHigt8bits)); System.out.println("3rd 8 bits are: " + Integer.toHexString(thirdHigh8bits)); System.out .println("right 8 bits are: " + Integer.toHexString(low8bits)); System.out.println("input is: " + Integer.toBinaryString(input)); System.out.println("left 8 bits are: (00000)" + Integer.toBinaryString(high8bits)); String secondHigt8bitsStr = Integer.toBinaryString(secondHigt8bits); System.out .println("2nd 8 bits are: " + secondHigt8bitsStr.substring(secondHigt8bitsStr .length() - 8)); String thirdHigh8bitsStr = Integer.toBinaryString(thirdHigh8bits); System.out.println("3rd 8 bits are: " + thirdHigh8bitsStr.substring(thirdHigh8bitsStr.length() - 8)); System.out.println("right 8 bits are: (0000000)" + Integer.toBinaryString(low8bits)); }
运行结果: input is: 5f5e101
left 8 bits are: 5
2nd 8 bits are: fffffff5
3rd 8 bits are: ffffffe1
right 8 bits are: 1
input is: 101111101011110000100000001
left 8 bits are: (00000)101
2nd 8 bits are: 11110101
3rd 8 bits are: 11100001
right 8 bits are: (0000000)1
可以看到BruteForceCoding.java使用了右移的方法进行编码,从左至右,每次取一个字节,如果使用ByteBuffer,编码为:使用int buffer,编码为:
由此可见Java的ByteBuffer和int buffer是如何简化我们工作的。