Is there an equivalent to memcpy() in Java?

前端 未结 9 1750
灰色年华
灰色年华 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:45

    You can use System.arrayCopy. It copies elements from a source array to a destination array. The Sun implementation uses hand-optimized assembler, so this is fast.

    0 讨论(0)
  • 2020-12-25 09:47

    Use System.arraycopy()

    System.arraycopy(sourceArray, 
                     sourceStartIndex,
                     targetArray,
                     targetStartIndex,
                     length);
    

    Example,

    String[] source = { "alpha", "beta", "gamma" };
    String[] target = new String[source.length];
    System.arraycopy(source, 0, target, 0, source.length);
    


    or use Arrays.copyOf()
    Example,

    target = Arrays.copyOf(source, length);
    

    java.util.Arrays.copyOf(byte[] source, int length) was added in JDK 1.6.

    The copyOf() method uses System.arrayCopy() to make a copy of the array, but is more flexible than clone() since you can make copies of parts of an array.

    0 讨论(0)
  • 2020-12-25 09:54

    If you just want an exact copy of a one-dimensional array, use clone().

    byte[] array = { 0x0A, 0x01 };
    byte[] copy = array.clone();
    

    For other array copy operations, use System.arrayCopy/Arrays.copyOf as Tom suggests.

    In general, clone should be avoided, but this is an exception to the rule.

    0 讨论(0)
  • 2020-12-25 09:57

    When you are using JDK 1.5+ You should use

    System.arraycopy()
    

    Instead of

    Arrays.copyOfRange()
    

    Beacuse Arrays.copyOfRange() wasn't added until JDK 1.6.So you might get

    Java - “Cannot Find Symbol” error
    

    when calling Arrays.copyOfRange in that version of JDK.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-25 10:02

    You can use System.arraycopy

    0 讨论(0)
提交回复
热议问题