为什么不是C具有二进制文字? [英] Why doesn't C have binary literals?
问题描述
我经常希望我可以做在C是这样的:
I am frequently wishing I could do something like this in c:
val1 |= 0b00001111; //clear high nibble
val2 &= 0b01000000; //set bit 7
val3 |= ~0b00010000; //clear bit 5
有了这个语法似乎是一个非常有用的除了到C没有缺点,我能想到的,它似乎像在那里位变换是相当普遍的一种低层次的语言很自然的事。
Having this syntax seems like an incredibly useful addition to C with no downsides that I can think of, and it seems like a natural thing for a low level language where bit-twiddling is fairly common.
编辑:我看到其他一些伟大的选择,但他们都土崩瓦解时,有一个更复杂的面具。例如,如果章
是一个微控制器控制I / O引脚的寄存器,我想设置引脚2,3,7高,同时我可以写 =章的0x46;
,但我不得不花费10秒想着它(我很可能不得不每次我读到后,这些code时候再花费10秒一个不看它一两天),或者我可以写 =章(1&LT;&LT; 1)| (1 <<; 2)| (1 LT; 6;);
但我个人认为这是比只是写不太清楚`章= 0b01000110;'我可以同意,它不超过8位很好地扩展或但也许16位架构。这并不是说我曾经需要做一个32位掩码。
I'm seeing some other great alternatives but they all fall apart when there is a more complex mask. For example, if reg
is a register that controls I/O pins on a microcontroller, and I want to set pins 2, 3, and 7 high at the same time I could write reg = 0x46;
but I had to spend 10 seconds thinking about it (and I'll likely have to spend 10 seconds again every time I read those code after a not looking at it for a day or two) or I could write reg = (1 << 1) | (1 << 2) | (1 << 6);
but personally I think that is way less clear than just writing `reg = 0b01000110;' I can agree that it doesn't scale well beyond 8 bit or maybe 16 bit architectures though. Not that I've ever needed to make a 32 bit mask.
推荐答案
据的理由国际标准 - 编程语言ç§6.4.4.1的整型常量的
According to Rationale for International Standard - Programming Languages C §6.4.4.1 Integer constants
添加二进制常量的建议被拒绝,由于缺乏precedent和效用不足。
A proposal to add binary constants was rejected due to lack of precedent and insufficient utility.
这不是标准C,但海湾合作委员会支持它由 0B
或 0B
:
It's not in standard C, but gcc supports it as an extension, prefixed by 0b
or 0B
:
i = 0b101010;
请参阅这里细节。
这篇关于为什么不是C具有二进制文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!