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

情到浓时终转凉″ 提交于 2019-12-02 13:03:41

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).

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