设置一个unsigned char的位与另一个unsigned char的另一个位,无条件 [英] Setting a bit of an unsigned char with the another bit of another unsigned char without conditional

查看:168
本文介绍了设置一个unsigned char的位与另一个unsigned char的另一个位,无条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用bitwise以这种方式打开和关闭位:

I use bitwise to turn bits on and off this way:

unsigned char myChar = ...some value
myChar |= 0x01 << N // turn on the N-th bit

myChar &= ~(0x01 << N) //turn off the N-th bit

现在,假设N的值是已知的,但set / unset操作取决于另一个unsigned char的位的值。
现在,我这样做:

Now, suppose the value of N is know but the set/unset operation depends on the value of a bit of another unsigned char. Since now, I'm doing this way:

if ((otherChar & (0x01 << M)) != 0)
{
    //M-th bit of otherChar is 1
    myChar |= 0x01 << N; 
}else
{
    myChar &= ~(0x01 << N);
}

这应该是一种从unsigned char另一个。

This should be a sort of "moving bit" operation from an unsigned char to another.

我的问题:
有没有办法这样做而不使用条件? (和没有std :: bitset)

My question: is there any way of doing this without using the conditional? (and without std::bitset too)

推荐答案

简短的回答是是。

更长的答案是直接从源代码中使用位:

The longer answer is that you use the bit directly from the source:

unsigned char bit = 1 << N;

myChar &= ~bit;             // Zero the bit without changing anything else
myChar |= otherChar & bit;  // copy the bit from the source to the destination.

这假设您想将位N从源复制到目标的位N.如果源和目标位可能在不同的偏移量,事情变得有点困难。你不仅从源中提取正确的位,但是你必须将它移动到正确的位置,然后OR它到目的地。基本思想是如上所述,但是移位代码有点繁琐。问题是你想做类似的事情:

This assumes you want to copy bit N from the source to bit N of the destination. If the source and destination bits might be at different offsets, things get a little more difficult. You have not only extract the correct bit from the source, but you then have to shift it to the correct place, then OR it into the destination. The basic idea is about like above, but the code for shifting is a little tedious. The problem is that you'd like to do something like:

unsigned char temp = source & 1 << M;
temp <<= N - M;
dest |= temp;

如果N> M,这将很好,但是如果M> N, temp <-<= -3; 。你会像会是一个左移位-3,结束为右移位3 - 但这不是发生了什么,所以你需要一些条件代码来获取绝对值和找出是做右移还是左移以使位从源到目的地中的正确位置。

This will work fine if N > M, but if M > N, you end up with something like temp <<= -3;. What you'd like would be for a left shift of -3 to end up as a right shift of 3 -- but that's not what happens, so you need some conditional code to take the absolute value and figure out whether to do a right shift or left shift to get the bit from the source into the correct spot in the destination.

这篇关于设置一个unsigned char的位与另一个unsigned char的另一个位,无条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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