使用1按位设置字节的所有位 [英] Using 1 to bitwise set all bits of a byte

查看:78
本文介绍了使用1按位设置字节的所有位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前像这样将值硬编码为255

I currently hardcode a value to 255 like so

uint8_t outStates       = 0xFF;

但是我有一个更干净使用的宏

But I have a macro that would be cleaner to use

#define TCA9555_LOW (1)

我想到的唯一方法就是这种方式,但是阅读效率低下且难看,hich不是我想要的

And the only way I would think of to do it would be this way, but is seems inefficient and uglier to read, hich is not what I want

for(int i = 0; i < 8; i++)
{
    outStates |= (TCA9555_LOW << i);
}

是否有一种更漂亮的方法,可以使用易于读取的值为1的宏一次设置所有位?

Is there a prettier way to set all bits at once, using an easy to read macro of value 1 ?

非常感谢!

推荐答案

您希望将每个位设置为 TCA9555_LOW 的值而不会循环.为此,您可以使用以下代码:

You want to to set each bit to the value of TCA9555_LOW without looping. To achieve that, you can use the following:

uint8_t outStates =
     ( TCA9555_LOW << 7 )
   | ( TCA9555_LOW << 6 )
   | ( TCA9555_LOW << 5 )
   | ( TCA9555_LOW << 4 )
   | ( TCA9555_LOW << 3 )
   | ( TCA9555_LOW << 2 )
   | ( TCA9555_LOW << 1 )
   | ( TCA9555_LOW << 0 );


但是,如果我们考虑一下,只有两种可能的结果.以下是等效的:


But if we think about it, there's only two possible outcomes. The following would be equivalent:

uint8_t outStates = TCA9555_LOW ? 0xFF : 0x00;


最后,在相同的基础上,我们可以使用以下内容:


Finally, on the same basis, we could use the following:

uint8_t outStates = 0;
if (TCA9555_LOW)
   outStates = ~outStates;


在前两种情况下,编译器应将表达式折叠为单个常量.甚至第三.


In the first two cases, the compiler should fold the expression into a single constant. Maybe even the third.

这篇关于使用1按位设置字节的所有位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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