Finding how many bits it takes to represent a 2's complement using only bitwise functions

冷暖自知 提交于 2019-12-02 22:45:12

问题


We can assume an int is 32 bits in 2's compliment The only Legal operators are: ! ~ & ^ | + << >>

At this point i am using brute force

int a=0x01;
x=(x+1)>>1; //(have tried with just x instead of x+1 as well)
a = a+(!(!x));

... with the last 2 statements repeated 32 times. This adds 1 to a everytime x is shifted one place and != 0 for all 32 bits

Using the test compiler it says my method fails on test case 0x7FFFFFFF (a 0 followed by 31 1's) and says this number requires 32 bits to represent. I dont see why this isnt 31 (which my method computes) Can anyone explain why? And what i need to change to account for this?


回答1:


0x7FFFFFFF does require 32 bits. It could be expressed as an unsigned integer in only 31 bits:

111 1111 1111 1111 1111 1111 1111 1111

but if we interpret that as a signed integer using two's complement, then the leading 1 would indicate that it's negative. So we have to prepend a leading 0:

0 111 1111 1111 1111 1111 1111 1111 1111

which then makes it 32 bits.

As for what you need to change — your current program actually has undefined behavior. If 0x7FFFFFFF (231-1) is the maximum allowed integer value, then 0x7FFFFFFF + 1 cannot be computed. It is likely to result in -232, but there's absolutely no guarantee: the standard allow compilers to do absolutely anything in this case, and real-world compilers do in fact perform optimizations that can happen to give shocking results when you violate this requirement. Similarly, there's no specific guarantee what ... >> 1 will mean if ... is negative, though in this case compilers are required, at least, to choose a specific behavior and document it. (Most compilers choose to produce another negative number by copying the leftmost 1 bit, but there's no guarantee of that.)

So really the only sure fix is either:

  • to rewrite your code as a whole, using an algorithm that doesn't have these problems; or
  • to specifically check for the case that x is 0x7FFFFFFF (returning a hardcoded 32) and the case that x is negative (replacing it with ~x, i.e. -(x+1), and proceeding as usual).



回答2:


Please try this code to check whether a signed integer x can be fitted into n bits. The function returns 1 when it does and 0 otherwise.

// http://www.cs.northwestern.edu/~wms128/bits.c
int check_bits_fit_in_2s_complement(signed int x, unsigned int n) {
  int mask = x >> 31;

  return !(((~x & mask) + (x & ~mask))>> (n + ~0));
}


来源:https://stackoverflow.com/questions/9122636/finding-how-many-bits-it-takes-to-represent-a-2s-complement-using-only-bitwise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!