Hwo to read bit and set same bit in different byte

Started by
21 comments, last by Misery 11 years, 6 months ago
#define COPY_BIT(x, i, y, j) (y) = ((y) & ~(1 << (j))) | ((((x) >> (i)) & 1) << (j))

Something like that...? Can probably be optimized better.
Advertisement
What patrrr wrote seems correct. I would do it with a function, though:
unsigned copy_bit(unsigned x, int i, unsigned y, int j) {
y &= ~(1u << j); // Clear y's j-th bit
y |= ((x >> i) & 1u) << j; // Copy x's i-th bit into position j
return y;
}


The fact that you need to use some funky name for the type and that you are going for lots of generality is only confusing matters, so start without that.
@alvaro & @patrrr: Thanks a lot Guys. That was exactly the thing I was looking for. biggrin.png
alvaro: at the moment I cannot even count how many times you have halped me. Special thanks and huge respect to your skills!

This topic is closed to new replies.

Advertisement