分配一个字节中的给定位 [英] Assigning a given bit in a byte

查看:64
本文介绍了分配一个字节中的给定位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在字节 B 中设置或清除给定位 i 非常简单(并经常记录),使用shift和按位运算:

Setting or clearing a given bit i in a byte B is straightforward (and often documented), using shift and bitwise operations:

B|= 1 << i;  // 1 shift, 1 or
B&= ~(1 << i); // 1 shift, 1 complement, 1 and



但是,不经常提到复制一位变量 b (而不是常量0或1)的值。这是我能想到的解决方案:


But copying the value of a one bit variable b (instead of the constant 0 or 1) is not so often mentioned. Here is a solution I can think of:

B= (B & ~(1 << i)) | (b << i); // 2 shifts, 1 complement, 1 and, 1 or



是否可以在较少的操作中执行此操作(当然不允许分支)?


Is it possible to do that in less operations (branches not allowed, of course) ?

推荐答案

此类问题的良好来源是 Bit Twiddling Hacks [ ^ ]。请参阅'为您的任务有条件地设置或清除没有分支的位'。添加生成掩码的指令,可以使用:

A good source for such problems is Bit Twiddling Hacks[^]. See 'Conditionally set or clear bits without branching' for your task. Adding an instruction to generate the mask, this can be used:
unsigned m = 1U << i;
B ^= (-b ^ B) & m;
// or
B = (B & ~m) | (-b & m);


这篇关于分配一个字节中的给定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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