您的位置:首页 > 其它

转自百度 整数与字节数组的转换

2012-02-12 17:47 288 查看
转自百度

http://wenku.baidu.com/view/3ac0c71db7360b4c2e3f6432.html

//整数到字节数组的转换
public static byte[] intToByte(int number) {
int temp = number;
byte[] b=new byte[4];
for (int i=b.length-1;i> -1;i--){
b[i] = new Integer(temp&0xff).byteValue(); //将最高位保存在最低位
temp = temp > > 8; //向右移8位
}
return b;
}

//字节数组到整数的转换
public static int byteToInt(byte[] b) {
int s = 0;
for (int i = 0; i < 3; i++) {
if (b[i] > = 0)
s = s + b[i];
else
s = s + 256 + b[i];
s = s * 256;
}
if (b[3] > = 0) //最后一个之所以不乘,是因为可能会溢出
s = s + b[3];
else
s = s + 256 + b[3];
return s;
}

public static int unsignedByteToInt(byte b) {
return (int) b & 0xFF;
}

}
Therefore for an array of 4 bytes (buf[]), which represents an integer :
int i = 0;
int pos = 0;
i += unsignedByteToInt(buf[pos++]) << 24;
i += unsignedByteToInt(buf[pos++]) << 16;
i += unsignedByteToInt(buf[pos++]) << 8;
I += unsignedByteToInt(buf[pos++]) << 0;
To convert a byte to it's hexadecimal equivalent
public static String byteToHex(byte b){
int i = b & 0xFF;
return Integer.toHexString(i);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  百度 byte integer string 360 c
相关文章推荐