1 原则:在计算机系统中,数值一律有补码来表示(存储). 所有的运算都以补码形式进行
2 补码:
正数的补码是其本身。6的补码是:00000110
负数的补码,通过对该数绝对值的补码按位取反,再对整个数加1,如-7,先计算7的补码为00000111,然后取反,得到11111000,然后再加1,得到1111001。
例子,计算 5&-6的结果
5的补码为00000101, -6的补码为11111010,
00000101
& 11111010
----------------------
00000000
所以结果为0
3 左移 右移 无符号移动
(1): 左移位运算符(<<)能将运算符左边的运算对象向左移动运算符右侧指定的位数(在低位补 0)。
不分正负数,相当于是左乘以2的n次方
(2):右移位运算符(>>)则将运算符左边的运算对象向右移动运算符右侧指定的位数
若值为正,则在高位插入0;若值为负,则在高位插入1。
(3):无符号移动 在执行运算时,>>>运算符的操作数高位补0
4 16进制与byte 数组之间的转换
/**
* Transform the specified byte into a Hex String form.
*/
public static final String bytesToHexStr(
byte[] bcd)
{
StringBuffer s = new StringBuffer(bcd.length * 2);
for (int i = 0; i < bcd.length; i++)
{
s.append(bcdLookup[(bcd[i] >>> 4) & 0x0f]);
s.append(bcdLookup[bcd[i] & 0x0f]);
}
return s.toString();
}
/**
* Transform the specified Hex String into a byte array.
*/
public static final byte[] hexStrToBytes(
String s)
{
byte[] bytes;
bytes = new byte[s.length() / 2];
for (int i = 0; i < bytes.length; i++)
{
bytes[i] = (byte)Integer.parseInt(
s.substring(2 * i, 2 * i + 2), 16);
}
return bytes;
}
private static final char[] bcdLookup =
{
'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'
};
4 常用进制之间相互转换
- 十进制转成十六进制:
- Integer.toHexString(int i)
- 十进制转成八进制
- Integer.toOctalString(int i)
- 十进制转成二进制
- Integer.toBinaryString(int i)
- 十六进制转成十进制
- Integer.valueOf("FFFF",16).toString()
- 八进制转成十进制
- Integer.valueOf("876",8).toString()
- 二进制转十进制
- Integer.valueOf("0101",2).toString()