主要学习网络字节和计算机上表示的整数之间相互转换以及和小端字节序的转换
package org.apache.mina.proxy.utils;
import java.io.UnsupportedEncodingException;
/**
* ByteUtilities.java - Byte manipulation functions.
* @since MINA 2.0.0-M3
*/
public class ByteUtilities {
/**
* Returns the integer represented by up to 4 bytes in network byte order.
* 把网络字节序的4字节转换成整数
* @param buf the buffer to read the bytes from
* @param start
* @param count
* @return
*/
public static int networkByteOrderToInt(byte[] buf, int start, int count) {
if (count > 4) {
throw new IllegalArgumentException(
"Cannot handle more than 4 bytes");
}
int result = 0;
//(这里面是考虑32位机器)采用与低8位字节做或操作,然后左移8位,把4个字节变成一个整数的32位
for (int i = 0; i < count; i++) {
result <<= 8;
result |= (buf[start + i] & 0xff);
}
return result;
}
/**
* Encodes an integer into up to 4 bytes in network byte order.
* 把一个整数编码成4个网络字节序的字节
* @param num the int to convert to a byte array
* @param count the number of reserved bytes for the write operation
* @return the resulting byte array
*/
public static byte[] intToNetworkByteOrder(int num, int count) {
byte[] buf = new byte[count];
intToNetworkByteOrder(num, buf, 0, count);
return buf;
}
/**
* Encodes an integer into up to 4 bytes in network byte order in the
* supplied buffer starting at <code>start</code> offset and writing
* <code>count</code> bytes.
*
* @param num the int to convert to a byte array
* @param buf the buffer to write the bytes to
* @param start the offset from beginning for the write operation
* @param count the number of reserved bytes for the write operation
*/
public static void intToNetworkByteOrder(int num, byte[] buf, int start,
int count) {
if