if java 负数,Java如何计算负数?

I use the ~ operation for bit manipulation, and I'm just wondering how Java calculates the negative number?

I checked the Java documentation:

"The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111"."

So if int a = 60 (0011 1100), then int c = ~a (1100 0011).

The question is, how Java calculate negative numbers so that 1100 0011 = -61? The only way 1100 0011 is calculated -61 is

the highest bit is the sign bit.

-2^6 + 2^1 + 2^0 = -61.

But this make no sense to me.

解决方案

The assumption that the highest bit is a simple sign bit is wrong. Java, as well as most modern programming languages (and hardware architectures) use the so-called two's complement representation for numbers. (The bit itself, coincidentally, does indicate the sign, but not in the way you would expect it to, i.e. 150 and -150 have more differences than just the sign bit in their representation.)

This representation might seem like an odd choice at first, but it actually makes operations such as adding a positive number to a negative number (or variations of this) automagically work, without making the processor have to check for special cases.

The system is useful in simplifying the implementation of arithmetic on computer hardware. Adding 0011 (3) to 1111 (−1) at first seems to give the incorrect answer of 10010. However, the hardware can simply ignore the left-most bit to give the correct answer of 0010 (2). Overflow checks still must exist to catch operations such as summing 0100 and 0100.

The system therefore allows addition of negative operands without a subtraction circuit and a circuit that detects the sign of a number. Moreover, that addition circuit can also perform subtraction by taking the two's complement of a number (see below), which only requires an additional cycle or its own adder circuit. To perform this, the circuit merely pretends an extra left-most bit of 1 exists.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值