将int转换成一个byte[]:
public static byte[] integerToBytes(int intValue) {
byte[] byteValue = new byte[4];
int shift = 0; for (int x = 0; x < 4; x++) {
shift -= 8;
byteValue[x] = (byte) (intValue >>> shift);
} return byteValue;
}将byte[]转换成int:
public static int bytesToInt(byte[] b) throws Exception {
int intValue = 0; if (b.length < 4) {
throw new Exception("byte array's length is less than 4");
} //只取b的前4位
for (int x = 0; x < 4; x++) {
intValue <<= 8;
intValue |= (b[x] & 0xFF);
} return intValue;
}希望对你有帮助
public static byte[] integerToBytes(int intValue) {
byte[] byteValue = new byte[4];
int shift = 0; for (int x = 0; x < 4; x++) {
shift -= 8;
byteValue[x] = (byte) (intValue >>> shift);
} return byteValue;
}将byte[]转换成int:
public static int bytesToInt(byte[] b) throws Exception {
int intValue = 0; if (b.length < 4) {
throw new Exception("byte array's length is less than 4");
} //只取b的前4位
for (int x = 0; x < 4; x++) {
intValue <<= 8;
intValue |= (b[x] & 0xFF);
} return intValue;
}希望对你有帮助
byte[] b=new byte[4];
int intTB=1024;
b[0]=(byte)(intTB&0x000000FF); //b[0]=0
b[1]=(byte)((intTB>>8)&0x000000FF); //b[1]=4
b[2]=(byte)((intTB>>16)&0x000000FF); //b[2]=0
b[3]=(byte)((intTB>>24)&0x000000FF); //b[3]=0//byte[] to int
int int105 = b[0]+(b[1]<<8)+(b[2]<<16)+(b[3]<<24);
还有,怎么给分奖励啊?
byte[2]到byte[5]是一个int, byte[6]到byte[13]是double,用hehecafe的方法的话,
怎么得到byte[10]的子数组?从2到5。
byte 8;char 16; short 16; int 32; float 32; long 64; double 64;
所以如hehecafe和Danger2000(飞鱼)的那样只要每次位移8位就能将各种类型变为byte了。
仍然谢谢各位。