10進法と2進法の相互変換
2012 ワード
/**
* @author 2010-4-1
* :
*/
public class IntAndByte {
/**
* byte
* @param num
* @return
*/
public static byte[] int2bytes(int num){
byte[] b=new byte[4];
int mask=0xff;
for(int i=0;i<4;i++){
b[i]=(byte)(num >>>(24-i*8));
}
return b;
}
/**
*
* @param b
* @return
*/
public static int bytes2int(byte[] b) {
//byte[] b=new byte[]{1,2,3,4};
int mask=0xff;
int temp=0;
int res=0;
for(int i=0;i<4;i++){
res<<=8;
temp=b[i]&mask;
res|=temp;
}
return res;
}
public static void main(String[] args) {
// byte[] b = int2bytes(20);
// System.out.println("b :"+b.length);
// String s = new String(b);
// System.out.println("s :"+s);
}
}
/**
* :
*/
/**
* int to byte
* @param i
* @return
*/
public static byte[] intToByte(int i) {
byte[] bt = new byte[4];
bt[0] = (byte) (0xff & i);
bt[1] = (byte) ((0xff00 & i) >> 8);
bt[2] = (byte) ((0xff0000 & i) >> 16);
bt[3] = (byte) ((0xff000000 & i) >> 24);
return bt;
}
/**
* byte to int
* @param bytes
* @return
*/
public static int bytesToInt(byte[] bytes) {
int num = bytes[0] & 0xFF;
num |= ((bytes[1] << 8) & 0xFF00);
num |= ((bytes[2] << 16) & 0xFF0000);
num |= ((bytes[3] << 24) & 0xFF000000);
return num;
}