您的位置:首页 > 其它

基本数据类型转换为byte数组

2016-10-02 17:15 232 查看
<span style="font-family: Arial, Helvetica, sans-serif;">/** long型转换成byte数组 */</span>
public static byte[] longToByte(long number) {
byte[] b = new byte[8];
longToByte(number, b, 0);
return b;
}
/** 将long型数据填充至指定byte数组 */
public static int longToByte(long number, byte[] buf, int offset) {
for (int i = 0; i < 8; i++) {
buf[offset+7-i] = (byte) (number & 0xff);// 将最低位保存在最低位
number = number >> 8; // 向右移8位
}
return offset + 8;
}
/** 将byte数组转成long型数据 */
public static long byteToLong(byte[] buf, int offset, int length) {
long result = 0;
for (int i = 0; i < length; i++) {
result = result << 8 | (buf[i+offset]&0xff);
}
return result;
}

/** int型转换成byte数组 */
public static byte[] intToByte(int number) {
byte[] b = new byte[4];
longToByte(number, b, 0);
return b;
}
/** 将int型数据填充至指定byte数组 */
public static int intToByte(int number, byte[] buf, int offset) {
for (int i = 0; i < 4; i++) {
buf[offset+3-i] = (byte) (number & 0xff);// 将最低位保存在最低位
number = number >> 8; // 向右移8位
}
return offset + 4;
}
/** 将byte数组转成int型数据 */
public static int byteToInt(byte[] buf, int offset, int length) {
int result = 0;
for (int i = 0; i < length; i++) {
result = result << 8 | (buf[i+offset]&0xff);
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: