计数所需的位的数目重新present在2的补的整数 [英] counting the number of bit required to represent an integer in 2's complement

查看:239
本文介绍了计数所需的位的数目重新present在2的补的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写数位重新present 2的补码形式的int所需数量的功能。要求:

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

目前,我想是这样的:

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;
}

然而,该算法不起作用。它也超过了90运营商的限制。任何建议,我怎么能修复并改善这种算法?

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

推荐答案

通过2的补整数,问题是负数。负数是由最显著位指示:如果它被设置,则数是负的。
一个2的补码整数n的负被定义为 - (1 n值的补数)+1结果。
因此,我将首先测试负号。如果它被设置,所需要的比特数目仅仅是比特可用来重新present的整数,例如数32位。如果没有,你可以简单地算由一位向右反复移动n所需的比特数,直到结果为零。如果n,例如,将是+1,例如000 ... 001,你不得不转移一次,以结果为右零,例如1次。因此,你需要1位重新present它。

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.

这篇关于计数所需的位的数目重新present在2的补的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆