本文介绍了在Java中将long [64]转换为byte [512]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将进程移植到Java。在C#和C ++中已经有了工作版本。

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

我在C#中有一个部分,我做Marshal.Copy(...)将64个ulongs转换为512个字节C ++中的一行我使用memmove(...)来做同样的事情。 Java中有哪些可以实现相同的结果?我需要相同的二进制信息,只需要字节而不是长字。

I have a section in C# that I do Marshal.Copy(...) to convert 64 ulongs to 512 bytes and that line in C++ I use memmove(...) to do the same thing. What is available in Java to achieve the same result? I need the same binary information in the same order just as bytes instead of longs.

编辑:

我移植到Java的原因是利用Java自然具有的可移植性。我不想使用本机代码。

The reason I'm porting to Java is to take advantage of the portability that Java naturally has. I would not like to use native code.

另一件事。由于Java不包含无符号值,因此我需要稍微改变一下我要求的内容。我想从64个long(C#和C ++中的ulongs)中的每一个获得8个无符号字节值,以便稍后我可以在数组中的索引处使用这些值。这需要发生数千次,所以最快的方式是最好的方式。

Another thing. Since Java doesn't contain unsigned values, then I need to change what I'm requesting by just a little. I would like to attain the 8 unsigned byte values from each of the 64 longs (ulongs in C# and C++) so that I can use those values at indices in arrays later. This needs to happen thousands of times so the fastest way would be the best way.

推荐答案

效果很好为此:只需输入64 long 值并使用获取 byte [] out array()方法。 类可以有效地处理字节序问题。例如,结合评论中建议的方法:

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();
}

附录:产生的字节[] 组件是有符号的8位值,但Java数组需要。将字节转换为 int 将导致符号扩展,但屏蔽较高位的位将给出无符号值 byte b

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;

这详细说明适用的运营商优先级规则。此相关演示了 double 值的类似方法。

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

这篇关于在Java中将long [64]转换为byte [512]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 17:19