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

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

问题描述

我用按位转位和关闭是这样的:

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的值是知道的,但设置/取消操作取决于对位的另一个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位。如果源和目标位可能会在不同的偏移,事情变得更加困难。您不仅提取从源头上正确的位,但你必须把它移动到正确的地方,当时还是入目的地。其基本思想是对像上面,但code代表变速是有点乏味。问题是,你想要做的是这样的:

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,你最终像温度&LT;&LT; = -3; 。你会的的将是-3左移落得为3右移 - 但是这不是发生什么事情,所以你需要一些条件code取绝对值并找出是否做右移或左移获得从源头位到目的地的正确的位置。

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天全站免登陆