Is there an equivalent to memcpy() in Java?

前端 未结 9 1826
灰色年华
灰色年华 2020-12-25 09:34

I have a byte[] and would like to copy it into another byte[]. Maybe I am showing my simple \'C\' background here, but is there an equivalent to memcpy() on byte arrays in

9条回答
  •  一个人的身影
    2020-12-25 09:57

    Use byteBufferViewVarHandle or byteArrayViewVarHandle.

    This will let you copy an array of "longs" directly to an array of "doubles" and similar with something like:

    public long[] toLongs(byte[] buf) {
        int end = buf.length >> 3;
        long[] newArray = new long[end];
        for (int ii = 0; ii < end; ++ii) {
            newArray[ii] = (long)AS_LONGS_VH.get(buf, ALIGN_OFFSET + ii << 3);
        }
    }
    
    private static final ALIGN_OFFSET = ByteBuffer.wrap(new byte[0]).alignmentOffset(8); 
    private static final VarHandle AS_LONGS_VH = MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.nativeOrder());
    

    This will let you do the bit hacking like:

    float thefloat = 0.4;
    int floatBits;
    _Static_assert(sizeof theFloat == sizeof floatBits, "this bit twiddling hack requires floats to be equal in size to ints");
    memcpy(&floatBits, &thefloat, sizeof floatBits);
    

提交回复
热议问题