Converting long[64] to byte[512] in Java?

后端 未结 1 986
暗喜
暗喜 2020-12-06 16:21

I\'m porting a process over to Java. There\'s already working versions in C# and C++.

I have a section in C# that I do Marshal.Copy(...) to convert 64 ulongs to 512

相关标签:
1条回答
  • 2020-12-06 17:27

    ByteBuffer works well for this: just put in 64 long values and get a byte[] out using the array() method. The ByteOrder class can handle endian issues effectively. For example, incorporating the approach suggested in a comment by wierob:

    private static byte[] xform(long[] la, ByteOrder order) {
        ByteBuffer bb = ByteBuffer.allocate(la.length * 8);
        bb.order(order);
        bb.asLongBuffer().put(la);
        return bb.array();
    }
    

    Addendum: The resulting byte[] components are signed, 8-bit values, but Java arrays require nonnegative integer index values. Casting a byte to an int will result in sign extension, but masking the higher order bits will give the unsigned value of byte b:

    int i = (int) b & 0xFF;
    

    This answer elaborates on the applicable operator precedence rules. This related answer demonstrates a similar approach for double values.

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