int to byte[]
1/ new String(new Integer(int value)).getBytes()
2/public synchronized static byte[] Int2Byte(int send) throws IOException
{
byte [] bTemp = new byte[4];
//System.out.println("send: "+send+ " Hex:" + Integer.toHexString(send));
for (int i=0;i<4;i++)
{
bTemp[i] = (byte)((send >>(i*8))& 0xff);
//System.out.println("send byte" +((send >>(i*16))&0xff));
}
// 取正
private int toInt(byte b){
if(b >= 0) return (int)b;
else return (int)(b + 256);
}
// 4 byte Array to int
private int byteArray4ToInt(byte[] byteValue){
if(byteValue.length != 4)
return 0;
int intValue = 0;
try{
intValue = toInt(byteValue[0]);
intValue = (intValue << 8) + toInt(byteValue[1]);
intValue = (intValue << 8) + toInt(byteValue[2]);
intValue = (intValue << 8) + toInt(byteValue[3]);
}
catch(Exception e){
e.printStackTrace();
}
return intValue;
}
----- 这是我项目里写的工具函数,要注意的是byte-->int的时候,如果是负数
----- 要+256,代码如上
整型与字节数组转换
本文介绍了一种将整型数值转换为字节数组的方法,并提供了将字节数组转换回整型数值的实用工具函数。特别注意了负数转换时的处理方式。
2357





