简体   繁体   中英

Bitwise arthmetric Will this result in true or false

Given three variables:

int x = rand();
int y = rand(); 
int z = x + y;

Is it always true that z + (~x + 1) is equal to y . Or is there a possible overflow that makes the result not equal to y ?

In twos-complement signed arithmetic with wraparound, (~x + 1) is equal to -x , so z + (~x + 1) is equal to z - x is equal to y , no matter what the original values of x and y were.

There are two possible reasons why a C implementation might not use twos-complement signed arithmetic with wraparound.

  1. The C standard still provides, in principle, for the possibility that the CPU doesn't use a twos-complement representation of negative numbers. This is unlikely to be relevant nowadays: the UNIVAC is the only example I know of that's still in production, and I'm actually surprised to discover that it is still in production.

  2. The C standard says that signed overflow has undefined behavior . That means the compiler is allowed to assume it never happens, and generate code that will produce arbitrarily nonsensical output (or even crash) if either addition overflows. This is likely to be relevant.

You can avoid both of these possibilities by declaring x , y , and z to be unsigned int instead of int . Then y + x + (~x + 1) is guaranteed to equal y .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM