如何用单行代码(C)设置和清除不同的位 [英] How to set and clear different bits with a single line of code (C)

查看:96
本文介绍了如何用单行代码(C)设置和清除不同的位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

data |= (1 << 3)在不中断其他位的情况下设置位(3). data &= ~(1 << 4)在不中断其他位的情况下复位位(4).如何在一条指令中完成两项任务?

data |= (1 << 3) sets bit (3) without disrupting other bits. data &= ~(1 << 4) resets bit (4) without disrupting other bits. How can I accomplish both tasks in a single instruction?

(因为这实际上仅是为了提高可读性,所以我计划以类似#define gpioHigh(x) <insert code>的可爱方式#define进行此操作.另一种方法是弄清楚如何正确地将gpio指针传递给我为此明确编写的函数中目的,但效果不佳

(As this is really only for readability, I plan on #defineing this in a cute way like #define gpioHigh(x) <insert code>. The alternative is to figure out how to correctly pass a gpio pointer into functions that I write expressly for this purpose, but eff that)

谢谢!

迈克

推荐答案

这不可能在一条指令中完成.这是因为您需要对不同的位执行3种可能的操作:

It's not possible in a single instruction. This is because there are 3 possible operations you need to do on the different bits:

  • 设置它们(第3位)
  • 清除它们(第4位)
  • 不理会他们(其他所有方面)

如何用由二进制数字组成的位掩码从三种可能性中选择一种?

How can you select from one of three possibilities with a bitmask made up of binary digits?

当然,您可以用一行完成该操作,例如:

Of course, you can do it with one line e.g:

data = (data | (1 << 3)) & ~(1 << 4)

这篇关于如何用单行代码(C)设置和清除不同的位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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