简体   繁体   English

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

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

Is there was a way to convert a hole array of bytes (lets say 1024) into an int array of total 256 integers without using something similar to this: 有没有一种方法可以将字节的空洞数组(比如说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;

An int array ? 一个int数组 No, there isn't. 不,没有。 You might be able to get other APIs that are similar to arrays, but even so they'll be doing something like that underneath. 您也许能够获得数组相似的其他API,但是即使如此,它们在下面也会做类似的事情。 For example, ByteBuffer.wrap(array).asIntBuffer() would do that: it'd give you an array-like API, but underneath it'd be doing exactly what you say. 例如, ByteBuffer.wrap(array).asIntBuffer()会做到这一点:它会为您提供类似于数组的API,但在其下面将完全按照您说的去做。

You can use Unsafe but probably shouldn't 您可以使用不安全,但可能不应该使用

    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