大小端的转换
参考代码,如下所示
//将整数按照小端存放,低字节出访低位
public static byte[] toLH(int n) {
byte[] b = new byte[4];
b[0] = (byte) (n & 0xff);
b[1] = (byte) (n >> 8 & 0xff);
b[2] = (byte) (n >> 16 & 0xff);
b[3] = (byte) (n >> 24 & 0xff);
return b;
}
/**
* 将int转为大端,低字节存储高位
*
* @param n
* int
* @return byte[]
*/
public static byte[] toHH(int n) {
byte[] b = new byte[4];
b[3] = (byte) (n & 0xff);
b[2] = (byte) (n >> 8 & 0xff);
b[1] = (byte) (n >> 16 & 0xff);
b[0] = (byte) (n >> 24 & 0xff);
return b;
}
java提供的类
@SuppressWarnings("unused")
public static byte[] appendInsertMsg(byte[] msg, BSONObject append) {
List<byte[]> tmp = Helper.splitByteArray(msg, 4);
byte[] msgLength = tmp.get(0);
byte[] remaining = tmp.get(1);
byte[] insertor = bsonObjectToByteArray(append);
int length = Helper.byteToInt(msgLength);
int messageLength = length + Helper.roundToMultipleXLength(insertor.length, 4);
ByteBuffer buf = ByteBuffer.allocate(messageLength);
if (EmeralddbConstants.SYSTEM_ENDIAN == EmeralddbConstants.LITTLE_ENDIAN) {
buf.order(ByteOrder.LITTLE_ENDIAN);
} else {
buf.order(ByteOrder.BIG_ENDIAN);
}
buf.putInt(messageLength);
buf.put(remaining);
buf.put(Helper.roundToMultipleX(insertor, 4));
return buf.array();
}
生产中的一段代码,可以参考。
// 创建12个字节的字节缓冲区
public static void main(String args[]){
ByteBuffer bb = ByteBuffer.wrap(new byte[12]);
// 存入字符串
bb.asCharBuffer().put("abdcef");
System.out.println(Arrays.toString(bb.array()));
// 反转缓冲区
bb.rewind();
// 设置字节存储次序
bb.order(ByteOrder.BIG_ENDIAN);
bb.asCharBuffer().put("abcdef");
System.out.println(Arrays.toString(bb.array()));
// 反转缓冲区
bb.rewind();
// 设置字节存储次序
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.asCharBuffer().put("abcdef");
System.out.println(Arrays.toString(bb.array()));
}
运行结果:
[0, 97, 0, 98, 0, 100, 0, 99, 0, 101, 0, 102]
[0, 97, 0, 98, 0, 99, 0, 100, 0, 101, 0, 102]
[97, 0, 98, 0, 99, 0, 100, 0, 101, 0, 102, 0]
对比前两次和第三次的运行结果,第三次明显是小端模式,前两次都是大端模式,java默认是大端(之所以有0,是因为java中char占用两个字节)。