public class DecToHex {
public static final char c[] =
{
'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F'
};
public static void main(String args[]) {
byte b = (byte)Integer.parseInt(args[0]);
//b在位移时会先自动转换成int后再位移,这是取出高四位
System.out.print(c[(b>>4) & 0x0f]);
//取出低4位
System.out.println(c[b & 0x0f]);
}
}
[size=medium]
比如输入的是150
b=二进制的 10010110
移位时自动转换为int型 11111111 11111111 11111111 10010110
位移四位取高位 11111111 11111111 11111111 11111001
与上0x0f(00001111)就得到高4位 1001
[/size]
public static int bytesToInt(byte[] b) {
int mask = 0xff; //0b00000000,00000000,00000000,11111111
int temp = 0;
int result = 0;
// int为32位,byte为8位
for(int i = 0; i < 4; i++) {
result <<= 8;
temp = b[i] & mask; // b为负时,在转为int时,前面会补1;为正时,补0
result |= temp;
}
return result;
}