for (int i = 0 ; i < 4 ; i++) byArray[i]=(BYTE)(iNum>>(i<<3));是不是这样?
public class test { public static void main(String[] args) { int iNum = 65534; byte[] byArray = new byte[4]; for (int i = 0; i < 4; i++) { byArray[i] = (byte) (iNum >> (i << 3)); System.out.println(byArray[i]); } } } 结果是: -2 -1 0 0 不太对阿
public class IntUtil { public static void print(byte b){ for (int i=0;i<8;i++){ if ((b&1<<(7-i))==0){ System.out.print("0"); }else{ System.out.print("1"); } } System.out.print(" "); } public static byte[] intToByteArray(int src){ byte[] b=new byte[4]; for (int i=0;i<4;i++){ b[i]=(byte)(src>>>(8*(3-i))); print(b[i]); } return b; } public static int ByteArrayToInt(byte[] src){ int b=0; for (int i=0;i<4;i++){ for (int j=0;j<8;j++){ if ((src[i]&1<<(7-j))==0){ b&=~(1<<((3-i)*8+(7-j))); }else{ b|=(1<<((3-i)*8+(7-j))); } } } return b; } public IntUtil() { } public static void main(String[] args) { for (int i=-1;i>-1000;i--){ System.out.println(ByteArrayToInt(intToByteArray(i))); } } }
byArray[i]=(BYTE)(iNum>>(i<<3));是不是这样?
int iNum = 65534;
byte[] byArray = new byte[4];
for (int i = 0; i < 4; i++) {
byArray[i] = (byte) (iNum >> (i << 3));
System.out.println(byArray[i]);
}
}
}
结果是:
-2
-1
0
0
不太对阿
public static void print(byte b){
for (int i=0;i<8;i++){
if ((b&1<<(7-i))==0){
System.out.print("0");
}else{
System.out.print("1");
}
}
System.out.print(" ");
}
public static byte[] intToByteArray(int src){
byte[] b=new byte[4];
for (int i=0;i<4;i++){
b[i]=(byte)(src>>>(8*(3-i)));
print(b[i]);
}
return b;
} public static int ByteArrayToInt(byte[] src){
int b=0;
for (int i=0;i<4;i++){
for (int j=0;j<8;j++){
if ((src[i]&1<<(7-j))==0){
b&=~(1<<((3-i)*8+(7-j)));
}else{
b|=(1<<((3-i)*8+(7-j)));
}
}
}
return b;
} public IntUtil() {
} public static void main(String[] args) {
for (int i=-1;i>-1000;i--){
System.out.println(ByteArrayToInt(intToByteArray(i)));
}
}
}