public class ScoreTest { public static void main(String[] args) { byte[] be = int2BytesBE(0xcc123abc); System.out.println(ByteUtil.bytes2StrSpace(be)); byte[] le = int2BytesLE(0xcc123abc); System.out.println(ByteUtil.bytes2StrSpace(le)); } public static byte[] int2BytesBE(int num) { return int2Bytes(num, true); } public static byte[] int2BytesLE(int num) { return int2Bytes(num, false); } public static byte[] int2Bytes(int num, boolean isBigEndian) { final int len = Integer.SIZE / Byte.SIZE; byte[] bys = new byte[len]; for(int i = 0; i < len; i++) { int shift = isBigEndian ? (len - 1 - i) * Byte.SIZE : (i * Byte.SIZE); bys[i] = (byte)((num >>> shift) & 0xff); } return bys; } }class ByteUtil { private final static char[] HEX = "0123456789abcdef".toCharArray(); private ByteUtil() { } public static String bytes2StrSpace(byte[] bys) { char[] chs = new char[bys.length * 3 - 1]; for(int i = 0, k = 0; i < bys.length; i++) { if(k > 0) { chs[k++] = ' '; } chs[k++] = HEX[(bys[i] >> 4) & 0xf]; chs[k++] = HEX[bys[i] & 0xf]; } return new String(chs); } }
写个蛋疼的硬编码public class Test { public static void main(String[] args) { int i=12345678; byte[] b=new byte[4]; for(int m = 0; m < b.length; m++){ b[m] =(byte)( i % 100); i /= 100; } } }
b[0]=(byte)(0xff & (i >> 24)) b[1]=(byte)(0xff & (i >> 16)) b[2]=(byte)(0xff & (i >> 8)) b[3]=(byte)(0xff & i)
c++没人理财了么?
byte[] be = int2BytesBE(0xcc123abc);
System.out.println(ByteUtil.bytes2StrSpace(be)); byte[] le = int2BytesLE(0xcc123abc);
System.out.println(ByteUtil.bytes2StrSpace(le));
} public static byte[] int2BytesBE(int num) {
return int2Bytes(num, true);
} public static byte[] int2BytesLE(int num) {
return int2Bytes(num, false);
} public static byte[] int2Bytes(int num, boolean isBigEndian) {
final int len = Integer.SIZE / Byte.SIZE;
byte[] bys = new byte[len];
for(int i = 0; i < len; i++) {
int shift = isBigEndian ? (len - 1 - i) * Byte.SIZE : (i * Byte.SIZE);
bys[i] = (byte)((num >>> shift) & 0xff);
}
return bys;
}
}class ByteUtil { private final static char[] HEX = "0123456789abcdef".toCharArray(); private ByteUtil() { } public static String bytes2StrSpace(byte[] bys) {
char[] chs = new char[bys.length * 3 - 1];
for(int i = 0, k = 0; i < bys.length; i++) {
if(k > 0) {
chs[k++] = ' ';
}
chs[k++] = HEX[(bys[i] >> 4) & 0xf];
chs[k++] = HEX[bys[i] & 0xf];
}
return new String(chs);
}
}
public static void main(String[] args) {
int i=12345678;
byte[] b=new byte[4];
for(int m = 0; m < b.length; m++){
b[m] =(byte)( i % 100);
i /= 100;
}
}
}
b[1]=(byte)(0xff & (i >> 16))
b[2]=(byte)(0xff & (i >> 8))
b[3]=(byte)(0xff & i)