问题描述
我们可以假设一个int是2的补32位
唯一合法运营商是: 〜&安培; ^ | + LT;< >>
We can assume an int is 32 bits in 2's complimentThe 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));
...
与最后2语句重复32次。这增加了1到每次x被转移一个地方!= 0的所有32位
...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
使用测试编译它说我的方法失败的测试用例为0x7FFFFFFF(0后跟31 1的),并说这个数字需要32位重新present。我不明白为什么这个心不是31(这我的方法计算),任何人都可以解释为什么吗?而我需要更改考虑到这一点?
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?
推荐答案
请试试这个code,以检查是否有符号整数的 X 的可装配成的 N 的位。当它,否则为0,则函数返回1。
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));
}
这篇关于发现它需要多少位只用按位函数重新present 2的补的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!