奔雷手文泰来
2018-11-20 11:42
public class Binary {
//将byte[]转换成long
public long byte2Long(byte[] arr){
long num = 0;
for (int i= 0; i < 8; i++) {
num += (long)((arr[i]&0xff)<<i*8) ;
}
return num;
}
//将long转换成byte[]
public byte[] long2Byte(long b){
byte[] bytes=new byte[8];
for (int i = 0; i < 8; i++) {
bytes[i]=(byte)((b>>i*8)&0xff);
}
return bytes;
}
public static void main(String[] args) {
Binary test=new Binary();
long b= 99999999999999999L;
byte[] bytes=test.long2Byte(b) ;
System.out.println(Arrays.toString(bytes));
System.out.println(test.byte2Long(bytes));
}
}转回来变成了1592608119
long类型的数不是有值域范围嘛,你这个明显超出范围了啊
过了一段时间回过头来看,在第7行与第8行之间插入 System.out.println(num);
发现打印出来的数据分别是:
255
65535
9043967
1569325055
1569325175
1569342839
1575830903
1592608119
然后我把第7行改成 num+=(long)(arr[i]&0xff)<<i*8;
结果就对了.
经分析byte是4字节的,最多只能左移4位,超过4位就会造成数据丢失,要先转换成long才能左移8位;
二进制基础
99813 学习 · 211 问题