简单的方法来设置/取消单个位 [英] Simple way to set/unset an individual bit

查看:131
本文介绍了简单的方法来设置/取消单个位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我使用这个设置/一个字节未设置的各个位:

Right now I'm using this to set/unset individual bits in a byte:

if (bit4Set)
   nbyte |= (1 << 4);
else
   nbyte &= ~(1 << 4);

但是,你不能这样做,在一个更​​简单/优雅的方式?如设置或在单一操作取消设置位?

But, can't you do that in a more simple/elegant way? Like setting or unsetting the bit in a single operation?

注:我知道我可以只写一个函数来做到这一点,我只是想知道,如果我不会重新发明轮子

Note: I understand I can just write a function to do that, I'm just wondering if I won't be reinventing the wheel.

推荐答案

当然!如果您展开这将是比较明显| = &安培; = 在code,但你可以这样写:

Sure! It would be more obvious if you expanded the |= and &= in your code, but you can write:

nbyte = (nbyte & ~(1<<4)) | (bit4Set<<4);

注意 bit4Set 必须是零或有一个 - 不是这方面的任何非零值 - 工作。

Note that bit4Set must be zero or one —not any nonzero value— for this to work.

这篇关于简单的方法来设置/取消单个位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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