开发者

Why is my 'count leading zero' program malfunctioning?

开发者 https://www.devze.com 2023-01-06 17:52 出处:网络
Here is code which returns number of leading zeros from Hacker\'s Delight book: #include <iostream>

Here is code which returns number of leading zeros from Hacker's Delight book:

#include <iostream>
using namespace std;

int nlz(unsigned x) {
int n;
if (x == 0) return(32);
n = 1;
if ((x >> 16) == 0) {n = n +16; x = x <<16;}

if ((x >> 24) == 0) {n = n + 8; x = x << 8;}
if ((x >> 28) == 0) {n = n + 4; x = x << 4;}
if ((x >> 30) == 0) {n = n + 2; x = x <开发者_StackOverflow中文版< 2;}
n = n - (x >> 31);
return n;
}

int main(){
    int x;
    cin>>x;
    cout<<nlz(x)<<endl;

     return 0;
}

and when I enter number 8 it return 8 and is it correct maybe it should return 3 yes?

8//1000


It returns the number of leading bits that is zero in an unsigned integer , and it assumes an integer is 32 bits.

8 is 0000 0000 0000 0000 0000 0000 0000 1000 binary, and it should return 28 for that, as there's 28 leading bits zero before the first 1 bit. If you're running this on something where an integer is not 32 bits, it won't work.


This algorithm will return the number of leading zero bits from a 32-bit value. I don't see how it would return 8 for an input of 8.

0

精彩评论

暂无评论...
验证码 换一张
取 消