 # Efficient bit twiddling in C

Bit copy: To set or clear a bit within a byte variable based upon a bit in the same or other byte variable try:

```(byte2 &= ~BITMASK2), (byte1 & BITMASK1) ? (byte2 |= BITMASK2) : 0;
```

Which could be encapsulated into a macro:

```#define setmask(b1, m1, b2, m2) (((b2) &= ~(m2)), ((b1) & (m1)) ? ((b2) |= (m2)) : 0)
```

which you would use thusly:

```        setmask(byte1, BITMASK1, byte2, BITMASK2);
```

The result for the PIC is:

```        bcf     _byte2,3
btfsc   _byte1,2
bsf     _byte2,3
```

Which is very effecient. If you don't want to clear the bit first (e.g. if it was a port pin) then it would be:

```(!(byte1 & BITMASK1) ? (byte2 &= ~BITMASK2) : 0), (byte1 & BITMASK1) ? (byte2 |= BITMASK2) : 0;
```

PIC - Bit operations@

Sign Extension: Extends the sign of a n value by invoking with SIGNEX(x, n-1)

```#define SIGNEX(v, sb) ((v) | (((v) & (1 << (sb))) ? ~((1 << (sb))-1) : 0))
```
Better, from:
https://graphics.stanford.edu/~seander/bithacks.html#VariableSignExtend
```unsigned b; // number of bits representing the number in x
int x;      // sign extend this b-bit number to r
int r;      // resulting sign-extended number
int const m = 1U << (b - 1); // mask can be pre-computed if b is fixed

x = x & ((1U << b) - 1);  // (Skip this if bits in x above position b are already zero.)
r = (x ^ m) - m;```
The code above requires four operations, but when the bitwidth is a constant rather than variable, it requires only two fast operations, assuming the upper bits are already zeroes.

Count bits set: Counting bits set by lookup table

```//table where value at addr is the number of bits set for that number
static const unsigned char BitsSetTable256 = {
#define B2(n) n,     n+1,     n+1,     n+2
#define B4(n) B2(n), B2(n+1), B2(n+1), B2(n+2)
#define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2)
B6(0), B6(1), B6(1), B6(2)
};

unsigned int v; // count the number of bits set in 32-bit value v
unsigned int c; // c is the total bits set in v

// Option 1:
c = BitsSetTable256[v & 0xff] +
BitsSetTable256[(v >> 8) & 0xff] +
BitsSetTable256[(v >> 16) & 0xff] +
BitsSetTable256[v >> 24];

// Option 2:
unsigned char * p = (unsigned char *) &v;
c = BitsSetTable256[p] +
BitsSetTable256[p] +
BitsSetTable256[p] +
BitsSetTable256[p];

// To initially generate the table algorithmically:
BitsSetTable256 = 0;
for (int i = 0; i < 256; i++) {
BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2];
}```

 file: /Techref/language/ccpp/bittwid.htm, 3KB, , updated: 2020/2/8 20:59, local time: 2020/8/3 05:30, TOP NEW HELP FIND:  3.237.89.4:LOG IN

 ©2020 These pages are served without commercial sponsorship. (No popup ads, etc...).Bandwidth abuse increases hosting cost forcing sponsorship or shutdown. This server aggressively defends against automated copying for any reason including offline viewing, duplication, etc... Please respect this requirement and DO NOT RIP THIS SITE. Questions?Please DO link to this page! Digg it! / MAKE! Efficient bit twiddling in C

After you find an appropriate page, you are invited to your to this massmind site! (posts will be visible only to you before review) Just type in the box and press the Post button. (HTML welcomed, but not the <A tag: Instead, use the link box to link to another page. A tutorial is available Members can login to post directly, become page editors, and be credited for their posts.

Attn spammers: All posts are reviewed before being made visible to anyone other than the poster.
 Did you find what you needed? "No. I'm looking for: " "No. Take me to the search page." "No. Take me to the top so I can drill down by catagory" "No. I'm willing to pay for help, please refer me to a qualified consultant" "No. But I'm interested. me at when this page is expanded."

.