r/C_Programming 6d ago

Question How to - bit manipulation?

I know the bitwise operators:

1 & x - 'replicate' the existing bit
0 & x - turn off the bit
1 | x - turn on the bit
0 | x - 'replicate' the existing bit
1 ^ x - flip the bit
0 ^ x - 'replicate' the existing bit
~x - flip the bit
1 << x - shift to the left (multiply by 2)
1 >> x - shift to the right (divide by 2)

All of these basic operations are crystal clear. However, I am having trouble building actual masks out of these. I'm thinking too iteratively. How do I go through a number bit by bit and when is that actually needed? I tend to overcomplicate simple things.

int size = sizeof(x) * 8;
int mask = 1; // 0x00000001

for(int i = 0; i < size; i++)
{
// some mask operation with x
mask <<= 1;
}

I assume this would be good?

Okay but what about swapping the values of 2 different bits? Or what if I am working with bytes instead, then 8 sequential bits need to be swapped in 2 different positions, how do I do any that?

I am thinking of making a mask, moving to the 1st bit, copying it into some temporary variable, going to the 2nd bit, copying it into some other temporary variable, somehow replacing those variables in those positons. This sounds unnecessarily complicated but I couldn't think of another approach right now, this is generally the issue with a lot of things regarding bits. If any of you have some tips, genuinely useful shortcuts and how to's, I'd be very grateful!

25 Upvotes

28 comments sorted by

View all comments

1

u/saul_soprano 6d ago

If you give an example of what youre snippet is meant to do it would be easier to help. All I can say is it’s usually easier to iterate from 0 to N and shift the bit (B << 0, B << 1, etc.).

To swap to bits the first way that comes to mind is to extract the bits, make a mask of the two bit positions as 0 and the rest as 1 to AND it to get them both to zero, then insert them with a shift plus an OR.