Java中的Integer.toBinaryString(i)可以将整数转化为二进制的字符串,不过这个没有输出前面额外的零。
有符号的整数 原码 反码 补码
47 00101111 00101111 00101111(正数补码和原码、反码相同,不能从字面理解)
-47 10101111 11010000 11010001(负数补码是在反码上加1)
- 字节8位、字16位、双字32位、四字64位。
- 1个字节可以表示256个数,表示有符号数范围是-128 ~ 127.
- 有符号数在计算机中以补码形式存储。
- 正数的最高位是0,负数的最高位是1。
- 正数的 原码 = 反码 = 补码
- 负数的 原码 和 正数的原码一样,只有符号位不一样。
- 负数的 反码 = 原码取反(符合为不变)
- 负数的 补码 = 反码+1;
- 因为计算机中只是存补码,总结下补码,正数的补码=它的原码,负数的补码=它正数原码取反+1;
位操作:( i 为一个有符号数)
【-i & i 】得到 i 最低位为1的数。应用【i==(-i & i)】i是不是0,或只有一个1.
看一些程序库里面的类型,总是喜欢定义为int,然后用位操作,这中方法应该效率高些,明显要比写成字符串然后比较要效率高很多,如:Zest中的connections的类型:
/**
* Style indicating that connections should show their direction by default.
*/
public static final int CONNECTIONS_DIRECTED = 1 << 1;
/**
* Style constant to indicate that connections should be drawn with solid
* lines (this is the default).
*/
public static final int CONNECTIONS_SOLID = 1 << 2;
/**
* Style constant to indicate that connections should be drawn with dashed
* lines.
*/
public static final int CONNECTIONS_DASH = 1 << 3;
/**
* Style constant to indicate that connections should be drawn with dotted
* lines.
*/
public static final int CONNECTIONS_DOT = 1 << 4;
/**
* Style constant to indicate that connections should be drawn with
* dash-dotted lines.
*/
public static final int CONNECTIONS_DASH_DOT = 1 << 5;
/**
* Bitwise ANDs the styleToCheck integer with the given style.
*
* @param style
* @param styleToCheck
* @return boolean if styleToCheck is part of the style
*/
public static boolean checkStyle(int style, int styleToCheck) {
return ((style & styleToCheck) == styleToCheck);
}
判断类型方便,快些。