繁体   English   中英

在Java中将字节数组转换为int数组

[英]Convert a byte array into an int array in java

有没有一种方法可以将字节的空洞数组(比如说1024)转换为总共256个整数的int数组,而无需使用类似以下内容的方法:

int result = 0;   
    result = b[0] & MASK;
    result = result + ((b[1] & MASK) << 8);
    result = result + ((b[2] & MASK) << 16);
    result = result + ((b[3] & MASK) << 24);            
return result;

一个int数组 不,没有。 您也许能够获得数组相似的其他API,但是即使如此,它们在下面也会做类似的事情。 例如, ByteBuffer.wrap(array).asIntBuffer()会做到这一点:它会为您提供类似于数组的API,但在其下面将完全按照您说的去做。

您可以使用不安全,但可能不应该使用

    try {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        UNSAFE = (Unsafe) theUnsafe.get(null);
    } catch (Exception e) {
        throw new AssertionError(e);
    }


    byte[] bytes = new byte[128];
    for (int i = 0; i < bytes.length; i++) bytes[i] = (byte) i;
    int[] ints = new int[bytes.length / Integer.BYTES];
    UNSAFE.copyMemory(bytes, Unsafe.ARRAY_BYTE_BASE_OFFSET, ints, Unsafe.ARRAY_INT_BASE_OFFSET, bytes.length);
    for (int i : ints)
        System.out.printf("%08x%n", i);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM