计算机基础 补码 位操作

Java中的Integer.toBinaryString(i)可以将整数转化为二进制的字符串,不过这个没有输出前面额外的零。

 

有符号的整数    原码    反码    补码
  47      00101111  00101111  00101111(正数补码和原码、反码相同,不能从字面理解)
 -47      10101111  11010000  11010001(负数补码是在反码上加1)

  1. 字节8位、字16位、双字32位、四字64位。
  2. 1个字节可以表示256个数,表示有符号数范围是-128 ~ 127.
  3. 有符号数在计算机中以补码形式存储。
  4. 正数的最高位是0,负数的最高位是1。
  5. 正数的 原码 = 反码 = 补码
  6. 负数的 原码 和 正数的原码一样,只有符号位不一样。
  7. 负数的 反码 = 原码取反(符合为不变)
  8. 负数的 补码 = 反码+1;
  9. 因为计算机中只是存补码,总结下补码,正数的补码=它的原码,负数的补码=它正数原码取反+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);
	}

 

判断类型方便,快些。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值