I need to store data as LITTLE_ENDIAN
instead of default BIG_ENDIAN
.
Here's my sample code:
for (int i = 0; i < logo.length; i++) {
logoArray[i] = ((Integer) logo[i]).byteValue();
logoArray[i] = (byte) (((logoArray[i] & 1) << 7) + ((logoArray[i] & 2) << 5) + ((logoArray[i] & 4) << 3)
+ ((logoArray[i] & 8) << 1) + ((logoArray[i] & 16) >> 1) + ((logoArray[i] & 32) >> 3)
+ ((logoArray[i] & 64) >> 5) + ((logoArray[i] & 128) >> 7));
}
How should it be rewritten with ByteBuffer, for LITTLE_ENDIAN
, as the following code doesn't work for me:
ByteBuffer record = ByteBuffer.allocate(logo.length);
record.order(ByteOrder.LITTLE_ENDIAN);
...
record.put(((Integer) logo[i])开发者_运维知识库.byteValue());
...
record.array(); // get
ByteBuffer will work for you, if you use putInt
and not put
.
record.putInt((Integer) logo[i]);
A byte array (as Integer.byteValue()
) has no "endianness" so it is stored as it is.
As andcoz says, the endian isn't taken into account when you put one byte at a time. Here is an example to show you how to do it:
import java.nio.*;
public class Test {
public static void main(String[] args) {
int[] logo = { 0xAABBCCDD, 0x11223344 };
byte[] logoLE = new byte[logo.length * 4];
ByteBuffer rec = ByteBuffer.wrap(logoLE).order(ByteOrder.LITTLE_ENDIAN);
for (int i = 0; i < logo.length; i++)
rec.putInt(logo[i]);
// Debug printouts...
System.out.println("logo:");
for (int b : logo)
System.out.println(Integer.toHexString((b < 0 ? b + 256 : b)));
System.out.println("\nlogoLE:");
int tmp = 0;
for (byte b : logoLE) {
System.out.print(Integer.toHexString((b < 0 ? b + 256 : b)));
if (++tmp % 4 == 0)
System.out.println();
}
}
}
Output:
logo:
aabbccdd
11223344
logoLE:
ddccbbaa
44332211
精彩评论