为什么 C 没有二进制文字? [英] Why doesn't C have binary literals?

查看:28
本文介绍了为什么 C 没有二进制文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常希望我能在 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.

我看到了其他一些不错的选择,但是当有更复杂的掩码时,它们都会分崩离析.例如,如果 reg 是控制微控制器上 I/O 引脚的寄存器,我想同时将引脚 2、3 和 7 设置为高电平,我可以编写 reg =0x46; 但我不得不花 10 秒钟来思考它(而且我可能会在一天或两天不看这些代码后每次阅读这些代码时再花 10 秒钟)或者我可以写reg = (1 <<1) |(1 << 2) |(1 << 6); 但我个人认为这比只写reg = 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.

推荐答案

根据国际标准的基本原理 - 编程语言 C §6.4.4.1 整数常量

According to Rationale for International Standard - Programming Languages C §6.4.4.1 Integer constants

由于缺乏先例和实用性不足,添加二进制常量的提议被拒绝.

A proposal to add binary constants was rejected due to lack of precedent and insufficient utility.

它不在标准 C 中,但 GCC 支持将其作为扩展名,前缀为 0b0B:

It's not in standard C, but GCC supports it as an extension, prefixed by 0b or 0B:

 i = 0b101010;

请参阅此处了解详情.

这篇关于为什么 C 没有二进制文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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