K& R中的位计数功能 [英] bit count function in K&R

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

问题描述

K& R撰写的"C编程语言"一书中有一个计数功能:

In the book "C Programming Language" by K&R, there is a bit count function:

int bitsCount(unsigned x)
{
    int b;
    for (b = 0; x != 0; x >>= 1)
        if (x & 01)
            b++;
    return b;
}

我的问题是为什么他们使用 x& 01 ,但不是 x& 1 x& 00000001 ?那不是01表示八进制1吗?

My question is why they use x & 01 but not x & 1 or x & 00000001? Isn't that 01 means octal 1?

推荐答案

显然,您是正确的,没关系. x & 01x & 1x & 0x1等将执行完全相同的操作(并且在每个明智的编译器中,生成完全相同的代码).您在这里看到的是作者的惯例,曾经是很标准的(但从来都不是普遍的),现在已经不那么了.在这种情况下,使用八进制是为了清楚表明正在进行按位运算.我敢打赌,作者也以八进制定义标志常量(意为按位或在一起).这是因为,例如010& amp;的推论要容易得多. 017,然后推论8& 15,因为您一次可以想到一个数字.今天,由于完全相同的原因,我发现使用十六进制更为普遍(按位运算一次只能使用一位数字).十六进制相对于八进制的优势在于,十六进制数字与字节很好地对齐,并且我希望在现代代码中看到使用十六进制常数编写的大多数按位运算(尽管琐碎常数小于10,我倾向于写为单个十进制数字;所以在这种情况下,我个人将使用x & 1而不是x & 0x1.

Semantically, you're correct, it doesn't matter. x & 01, x & 1, x & 0x1, etc will all do the exact same thing (and in every sane compiler, generate the exact same code). What you're seeing here is an author's convention, once pretty standard (but never universal), now much less so. The use of octal in this case is to make it clear that bitwise operations are taking place; I'd wager that the author defines flag constants (intended to be bitwise-or'd together) in octal as well. This is because it's much easier to reason about, say, 010 & 017, then to reason about 8 & 15, as you can think about it one digit at a time. Today, I find it much more common to use hex, for exactly the same reason (bitwise operations apply one digit at a time). The advantage of hex over octal is that hex digits align nicely to bytes, and I'd expect to see most bitwise operations written with hex constants in modern code (although trivial constants < 10 I tend to write as a single decimal digit; so I'd personally use x & 1 rather than x & 0x1 in this context).

这篇关于K&amp; R中的位计数功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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