计算无符号整数中的位数 [英] Count number of bits in an unsigned integer

查看:149
本文介绍了计算无符号整数中的位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在文件中编写一个名为bitCount()的函数:bitcount.c,该函数返回其无符号整数参数的二进制表示形式的位数.

I want to write a function named bitCount() in the file: bitcount.c that returns the number of bits in the binary representation of its unsigned integer argument.

这是我到目前为止所拥有的:

Here is what I have so far:

#include <stdio.h>

int bitCount (unsigned int n);

int main () {
    printf ("# 1-bits in base 2 representation of %u = %d, should be 0\n",
        0, bitCount (0));
    printf ("# 1-bits in base 2 representation of %u = %d, should be 1\n",
        1, bitCount (1));
    printf ("# 1-bits in base 2 representation of %u = %d, should be 16\n",
        2863311530u, bitCount (2863311530u));
    printf ("# 1-bits in base 2 representation of %u = %d, should be 1\n",
        536870912, bitCount (536870912));
    printf ("# 1-bits in base 2 representation of %u = %d, should be 32\n",
        4294967295u, bitCount (4294967295u));
    return 0;
}

int bitCount (unsigned int n) {
    /* your code here */
}

好吧,当我运行它时,我得到:

Okay, when I just run this I get:

# 1-bits in base 2 representation of 0 = 1, should be 0
# 1-bits in base 2 representation of 1 = 56, should be 1
# 1-bits in base 2 representation of 2863311530 = 57, should be 16
# 1-bits in base 2 representation of 536870912 = 67, should be 1
# 1-bits in base 2 representation of 4294967295 = 65, should be 32

RUN SUCCESSFUL (total time: 14ms)

它没有返回正确的位数.

It doesn't return the correct numbers of bits.

在C中返回其无符号整数参数的二进制表示形式的位数的最佳方法是什么?

What's the best way to return the number of bits in the binary representation of its unsigned integer argument in C?

推荐答案

 int bitCount(unsigned int n) {

    int counter = 0;
    while(n) {
        counter += n % 2;
        n >>= 1;
    }
    return counter;
 }

这篇关于计算无符号整数中的位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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