Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

porting

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 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.

Edit:

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.

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.

like image 344
Corey Ogburn Avatar asked Feb 06 '10 03:02

Corey Ogburn


People also ask

Can we convert long to byte in Java?

Long class has the following methods for converting long type value to other primitive types. byte byteValue() returns the value of this Long as a byte. double doubleValue() returns the value of this Long as a double. float floatValue() returns the value of this Long as a float.

How do I convert a byte array to Base64 in Java?

In Java to convert a byte[] array to Base64 String we can use the Base64. getEncoder(). encodeToString() method. byte[] byteData = new byte[] {83, 105, 109, 112, 108, 101, 32, 83, 111, 108, 117, 116, 105, 111, 110}; String base64String = Base64.

How do I convert files to bytecode?

Step 1: Create an ASP.Net application and add a class Document. Step 2: Create a file of format doc/pdf/rtf etc. and convert the file content to a ByteArray using the following method. Then create an object of type Document and assign the Docname and DocContent property values from filename and filecontent.


1 Answers

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.

like image 60
trashgod Avatar answered Sep 17 '22 15:09

trashgod