转自百度 整数与字节数组的转换
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);
}
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);
}
相关文章推荐
- Java整数-字节,字节-字符,字节数组-十六进制字符串转换
- Java整数-字节,字节-字符,字节数组-十六进制字符串转换
- 整数和字节数组之间的转换算法
- 主题:Java整数-字节,字节-字符,字节数组-十六进制字符串转换
- 将一个字节数组从任意字节offset开始,长为len的字节转换为整数
- C++ 字节数组的转换(C++编程思想-数据抽象例子分析)
- 加密解密基础问题:字节数组和(16进制)字符串的相互转换
- 将字节数组转换为十六进制值字符串时 Byte 的用法
- C# 16进制与字符串、字节数组之间的转换
- C# 16进制与字符串、字节数组之间的转换
- C# 图片与字节数组(byte[])二进制相互转换,获取大小像素扩展名
- java 对象 转换成字节数组发送给服务器,根据服务器返回的字节数组自动组装成java对象。
- c#中字节数组byte[]、图片image、流stream,字符串string、内存流MemoryStream、文件file,之间的转换
- 字符串String转换成字节数组 byte[]的表现形式
- 字节字符和整数转换-大小端转换-结构体内存(文件)对齐规则之总结
- Java 中没有无符号数,在读字节数组转换的时候需要注意溢出的情况
- 字节数组与String类型的转换
- 字节数组、16进制数的字符串的相互转换
- Java中二进制、十进制、十六进制及ASCII码与String及字节数组与十六进制之间的转换
- 字符串 (string)与字节数组(byte[])之间的转换