java中数字的大小端问题

java中数字的大小端问题

结论

计算机中既可以是大端存储,也可以小端存储,跟CPU架构有关,IA架构(Intel、AMD)的CPU中是Little-Endian,而PowerPC 、SPARC和Motorola处理器是Big-Endian, 而java提供了两种方式,默认方式为大端。

代码分析

基于Java8,在Java中提供了一个api可以获取CPU使用的字节序:

ByteOrder byteOrder = ByteOrder.nativeOrder();
System.out.print(byteOrder);

运行结果:
在这里插入图片描述

源码解析

ByteOrder.nativeOrder() 源码,其最后调用了Bits.byteOrder()

	/**
     * Retrieves the native byte order of the underlying platform.
     *
     * <p> This method is defined so that performance-sensitive Java code can
     * allocate direct buffers with the same byte order as the hardware.
     * Native code libraries are often more efficient when such buffers are
     * used.  </p>
     *
     * @return  The native byte order of the hardware upon which this Java
     *          virtual machine is running
     */
    public static ByteOrder nativeOrder() {
        return Bits.byteOrder();
    }

Bits主要代码

private static final ByteOrder byteOrder;

static ByteOrder byteOrder() {
   if (byteOrder == null)
   	throw new Error("Unknown byte order");
   return byteOrder;
}
static {
   long a = unsafe.allocateMemory(8);
   try {
       unsafe.putLong(a, 0x0102030405060708L);
       byte b = unsafe.getByte(a);
       switch (b) {
       	case 0x01: byteOrder = ByteOrder.BIG_ENDIAN;     break;
       	case 0x08: byteOrder = ByteOrder.LITTLE_ENDIAN;  break;
       	default:
       		assert false;
   			byteOrder = null;
   	}
   } finally {
   	unsafe.freeMemory(a);
   }
}

JAVA设置数字二进制存储方式

对于Java,其实既有使用大端,也有使用小端,对于ByteBuffer,默认使用的Big-Endian(大端),也可以对默认方式进行修改,如下例子

int x = 0x01020304;

ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[4]);
byteBuffer.asIntBuffer().put(x);
String before = Arrays.toString(byteBuffer.array());
System.out.println("默认字节序:"+byteBuffer.order().toString() + "," + "内存数据:"+before);

byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
byteBuffer.asIntBuffer().put(x);
String after = Arrays.toString(byteBuffer.array());
System.out.println("修改字节序:"+byteBuffer.order().toString()+","+"内存数据:"+after);

默认字节序:BIG_ENDIAN,内存数据:[1, 2, 3, 4]
修改字节序:LITTLE_ENDIAN,内存数据:[4, 3, 2, 1]

bigEndian表示是否是大端,默认为true,所以后面put的时候实际是往ByteBufferAsIntBufferB大端中存储数据,但也可以调整为使用小端来存储数据,byteBuffer.order(ByteOrder.LITTLE_ENDIAN);

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值