Bit Manipulation
Setting a single bit
val |= 1u << n;
Clearing a bit
val &= ~(1u << n);
Toggling a bit
val ^= 1u << n;
Setting a bit to a specified value
One strategy is to clear the bit first and then set it to x
in a second step if necessary.
val &= ~(1u << n);
val |= x << n;
It’s possible to combine these two lines.
val = (val & ~(1u << n)) | (x << n);
Checking a bit
bit = (val >> n) & 1u;
Swapping bytes
Swapping bytes is very useful to convert between Little- and Big-Endian. Here’s an example for a byte swap on a 64bit integer.
uint64 bswap(uint64 x)
{
return ((x & 0xff00000000000000u) >> 56u)
| ((x & 0x00ff000000000000u) >> 40u)
| ((x & 0x0000ff0000000000u) >> 24u)
| ((x & 0x000000ff00000000u) >> 8u)
| ((x & 0x00000000ff000000u) << 8u)
| ((x & 0x0000000000ff0000u) << 24u)
| ((x & 0x000000000000ff00u) << 40u)
| ((x & 0x00000000000000ffu) << 56u);
}
Interestingly most compilers are able to compile this code with a single machine instruction, so no need for assembler to speed this up.
bswap:
mov rax, rdi
bswap rax
ret