Setting a bit of an unsigned char with the another bit of another unsigned char without conditional

寵の児 提交于 2019-12-22 11:18:23

问题


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

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);
}

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

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


回答1:


The short answer is "yes".

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.

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;

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.




回答2:


One solution is to first always unset the bit, and then bitwise-or in an appropriately shifted and masked version of otherChar.




回答3:


This reads the from bit of c1 and writes it to the to bit of c2.

#include <stdio.h>

typedef unsigned char uchar;

uchar move_bit(uchar c1, int from, uchar c2, int to)
{
    int bit;
    bit = (c1 >> from) & 1;            /* Get the source bit as 0/1 value */
    c2 &= ~(1 << to);                  /* clear destination bit */
    return (uchar)(c2 | (bit << to));  /* set destination bit */
}

int main()
{
    printf("%02X\n",move_bit(0x84,3,0x42,5));
    printf("%02X\n",move_bit(0x81,0,0x03,7));
    printf("%02X\n",move_bit(0xEF,4,0xFF,6));
    return 0;
}

Result:

42
83
BF


来源:https://stackoverflow.com/questions/11170740/setting-a-bit-of-an-unsigned-char-with-the-another-bit-of-another-unsigned-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!