Java中大小端的处理

大小端的转换

参考代码,如下所示

//将整数按照小端存放,低字节出访低位
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占用两个字节)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值