字节数组与int类型之间的转换
int占4个字节,一个字节8位
java中的byte是有符号的,范围是-128~127
将int转换为长度为4的字节数组
import java.util.Arrays;
import java.util.Scanner;
public class IntConversionByte {
public static byte[] conversion(int n){
byte[] a = new byte[4];
for(int i = 0; i < 4; i++)
a[i] = (byte)(n >> 8 * i);
return a;
}
public static void main(String[] args){
Scanner cin = new Scanner(System.in);
//Arrays.toString()用来之间输出数组元素,省去循环
//01011100 00001110 00001011 01001111(二进制原码)
//切记存的是补码
//92 14 11 79
System.out.println(Arrays.toString(conversion(1544424271)));
}
}
从低位到高位输出

将长度为4的字节数组转换为int
import java.util.Scanner;
public class ByteConversionInt {
public static int conversion(byte[] a){
int res = 0;
for(int i = 3; i >= 0; i--){
res = res << 8 | a[i] & 0xff;
}
return res;
}
public static void main(String[] str){
Scanner cin = new Scanner(System.in);
byte a[] = new byte[4];
for(int i = 0; i < 4; i++)
a[i] = cin.nextByte();
System.out.println(conversion(a));
}
}
从低位到高位输入

浙公网安备 33010602011771号