Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I copy 2 bits from one int to another?

I have two unsigned int numbers: a and b (b is an unsigned int pointer). I want to copy 8th and 9th bit of a to 2nd and 3rd bit of b(all indices are 0 based).

This is how I am doing it:

 bool secondBit =  (a & (1 << 8) ) ;
 bool thirdBit =   (a & (1 << 9) ) ;

 if (secondBit) {
     *b |= (1u << 2);
 }
 if (thirdBit) {
     *b |= (1u << 3);

Reminder: b is an unsigned int pointer.

Is there a better way of doing this ?

like image 849
brainydexter Avatar asked Mar 21 '14 17:03

brainydexter


People also ask

How do Bitwise operators work in C?

Binary AND Operator copies a bit to the result if it exists in both operands. Binary OR Operator copies a bit if it exists in either operand. Binary XOR Operator copies the bit if it is set in one operand but not both.


2 Answers

Clear the relevant bits of *b and set them to the bits you want from a:

*b = (*b & ~0xC) | ((a & 0x300) >> 6);

// This is the 'not' of 00001100, in other words, 11110011
~0xC;

// This zeros the bits of *b that you do not want (b being a pointer)
*b & ~0xC;   // *b & 11110011

//This clears all of a except the bits that you want
a & 0x300;

// Shift the result into the location that you want to set in *b (bits 2 and 3)   
((a & 0x300) >> 6);

// Now set the bits into *b without changing any other bits in *b
*b = (*b & ~0xC) | ((a & 0x300) >> 6);
like image 103
Michael Avatar answered Oct 05 '22 12:10

Michael


Depends on your definition of "better" :)

But, well, there is the std::bitset class in C++. Perhaps it suits your needs by offering a less error-prone interface.

like image 22
Christian Hackl Avatar answered Oct 05 '22 13:10

Christian Hackl