counting the number of bit required to represent an integer in 2's complement

元气小坏坏 提交于 2019-12-12 03:49:11

问题


I have to write a function that count the number of bit required to represent an int in 2's complement form. The requirement:

1. can only use: ! ~ & ^ | + << >>
2. no loops and conditional statement
3. at most, 90 operators are used

currently, I am thinking something like this:

int howManyBits(int x) {
   int mostdigit1 = !!(0x80000000 & x);
   int mostdigit2 = mostdigit1 | !!(0x40000000 & x);
   int mostdigit3 = mostdigit2 | !!(0x20000000 & x);
   //and so one until it reach the least significant digit
   return mostdigit1+mostdigit2+...+mostdigit32+1;
}

However, this algorithm doesn't work. it also exceed the 90 operators limit. any suggestion, how can I fix and improve this algorithm?


回答1:


With 2's complement integers, the problem are the negative numbers. A negative number is indicated by the most significant bit: If it is set, the number is negative. The negative of a 2's complement integer n is defined as -(1's complement of n)+1.
Thus, I would first test for the negative sign. If it is set, the number of bits required is simply the number of bits available to represent an integer, e.g. 32 bits. If not, you can simply count the number of bits required by shifting repeatedly n by one bit right, until the result is zero. If n, e.g., would be +1, e.g. 000…001, you had to shift it once right to make the result zero, e.g. 1 times. Thus you need 1 bit to represent it.



来源:https://stackoverflow.com/questions/15867003/counting-the-number-of-bit-required-to-represent-an-integer-in-2s-complement

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