title |
subtitle |
summary |
authors |
tags |
categories |
date |
lastmod |
featured |
draft |
image |
projects |
Bit magic in C (and C++) |
|
|
|
|
|
2020-06-13T19:01:19+02:00 |
2020-06-13T19:01:19+02:00 |
false |
true |
caption |
focal_point |
preview_only |
|
|
false |
|
|
Set a bit
// Set one bit high at position "bit" in input and store to output
output = input | (1 << bit);
// Shorthand
variable |= (1 << bit);
Clear a bit
// Clear one bit high at position "bit" in input and store to output
output = input & ~(1 << bit);
// Shorthand
variable &= ~(1 << bit);
Toggle a bit
// Clear one bit high at position "bit" in input and store to output
output = x ^ (1 << bit);
// Shorthand
variable ^= (1 << bit);