如何找到无符号幅度和 2 的补码的最小位数?
How do I find the minimum number of bits for unsigned magnitude and 2's compliment?
我对找到无符号大小和 2 的补码的最小位数有点困惑。
到目前为止,这是我的推理:
例如,
a) 243 decimal
Since 2^8 = 256, Unsigned and 2's compliment would both need a minimum 8 bits.
b) -56 decimal
This is impossible for unsigned.
2^6 = 64. One more bit is needed to show it is negative, so minimum 7 bits.
我的推理是否正确?
unsigned 的 "bits needed" 只是最高有效位(+1,取决于 MSB 的定义),对于二进制补码,您可以将该值取反并减一使其为正,然后为符号标志添加另一位。
int LeadingZeroCount(long value) {
// http://en.wikipedia.org/wiki/Hamming_weight
unsigned long x = value;
x |= (x >> 1); x |= (x >> 2); x |= (x >> 4);
x |= (x >> 8); x |= (x >> 16); x |= (x >> 32);
x -= (x >> 1) & 0x5555555555555555;
x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333);
x = (x + (x >> 4)) & 0x0F0F0F0F0F0F0F0F;
x += x >> 8; x += x >> 16; x += x >> 32;
return (sizeof(value) << 3) - (x & 0x7F);
}
int MostSignificantBit(long value) {
return (sizeof(value) << 3) - LeadingZeroCount(value);
}
int BitsNeededUnsigned(unsigned long value) {
return MostSignificantBit(value);
}
int BitsNeededTwosComplement(long value) {
if (value < 0)
return BitsNeededUnsigned(-value - 1) + 1;
else
return BitsNeededUnsigned(value);
}
int main() {
printf("%d\n", BitsNeededUnsigned(243));
printf("%d\n", BitsNeededTwosComplement(243));
printf("%d\n", BitsNeededTwosComplement(-56));
return 0;
}
至少,这是基于您对问题的定义。对我来说,+243 似乎需要 9 位作为二进制补码,因为符号位的 0 仍然相关。
我对找到无符号大小和 2 的补码的最小位数有点困惑。 到目前为止,这是我的推理: 例如,
a) 243 decimal
Since 2^8 = 256, Unsigned and 2's compliment would both need a minimum 8 bits.
b) -56 decimal
This is impossible for unsigned.
2^6 = 64. One more bit is needed to show it is negative, so minimum 7 bits.
我的推理是否正确?
unsigned 的 "bits needed" 只是最高有效位(+1,取决于 MSB 的定义),对于二进制补码,您可以将该值取反并减一使其为正,然后为符号标志添加另一位。
int LeadingZeroCount(long value) {
// http://en.wikipedia.org/wiki/Hamming_weight
unsigned long x = value;
x |= (x >> 1); x |= (x >> 2); x |= (x >> 4);
x |= (x >> 8); x |= (x >> 16); x |= (x >> 32);
x -= (x >> 1) & 0x5555555555555555;
x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333);
x = (x + (x >> 4)) & 0x0F0F0F0F0F0F0F0F;
x += x >> 8; x += x >> 16; x += x >> 32;
return (sizeof(value) << 3) - (x & 0x7F);
}
int MostSignificantBit(long value) {
return (sizeof(value) << 3) - LeadingZeroCount(value);
}
int BitsNeededUnsigned(unsigned long value) {
return MostSignificantBit(value);
}
int BitsNeededTwosComplement(long value) {
if (value < 0)
return BitsNeededUnsigned(-value - 1) + 1;
else
return BitsNeededUnsigned(value);
}
int main() {
printf("%d\n", BitsNeededUnsigned(243));
printf("%d\n", BitsNeededTwosComplement(243));
printf("%d\n", BitsNeededTwosComplement(-56));
return 0;
}
至少,这是基于您对问题的定义。对我来说,+243 似乎需要 9 位作为二进制补码,因为符号位的 0 仍然相关。