发一个JAVA将小端序转大端序的代码块。。。
public static short LowToShort(short a) {
return (short)(((a & 0xFF) << 8) | ((a >> 8) & 0xFF));
}
public static int LowToInt(int a) {
return (((a & 0xFF) << 24) | (((a >>8) & 0xFF) << 16) | (((a >> 16) & 0xFF) << 8) | ((a >> 24) & 0xFF));
}
public static short LowToShort(short a) {
return (short) (((a & 0xFF) << 8) | ((a >> 8) & 0xFF));
}
public static int LowToInt(int a) {
return (((a & 0xFF) << 24) | (((a >> 8) & 0xFF) << 16) | (((a >> 16) & 0xFF) << 8) | ((a >> 24) & 0xFF));
}
另外2个整型的方法
public static void printLittleEndian(int i) {
byte[] b = new byte[4];
b[0] = (byte) (0xff & i);
b[1] = (byte) ((0xff00 & i) >> 8);
b[2] = (byte) ((0xff0000 & i) >> 16);
b[3] = (byte) ((0xff000000 & i) >> 24);
for (byte c : b) {
System.out.print("0x" + Integer.toHexString(c & 0xFF) + ",");
}
System.out.println();
}
public static void printBigEndian(int i) {
byte[] b = new byte[4];
b[3] = (byte) (0xff & i);
b[2] = (byte) ((0xff00 & i) >> 8);
b[1] = (byte) ((0xff0000 & i) >> 16);
b[0] = (byte) ((0xff000000 & i) >> 24);
for (byte c : b) {
System.out.print("0x" + Integer.toHexString(c & 0xFF) + ",");
}
System.out.println();
}
public static void printBigEndian2(int i) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
dos.writeInt(i);
dos.flush();
bos.flush();
byte[] data = bos.toByteArray();
dos.close();
bos.close();
for (byte c : data) {
System.out.print("0x" + Integer.toHexString(c & 0xFF) + ",");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int toLittleEndian(int i) {
byte[] b = new byte[4];
b[0] = (byte) (0xff & i);
b[1] = (byte) ((0xff00 & i) >> 8);
b[2] = (byte) ((0xff0000 & i) >> 16);
b[3] = (byte) ((0xff000000 & i) >> 24);
return b[3] & 0xFF | (b[2] & 0xFF) << 8 | (b[1] & 0xFF) << 16
| (b[0] & 0xFF) << 24;
}
大端序把最后返回的顺序改下即可。
本文链接:https://it72.com:4443/2136.htm