1
0
jcktrue.dk/content/post/bit-magic/index.md
Jens True 049a568c60
All checks were successful
continuous-integration/drone/push Build is passing
Cleanup code highlighting
2021-05-17 16:35:11 +02:00

64 lines
1.3 KiB
Markdown

---
title: "Bit magic in C (and C++)"
subtitle: "Tips and trick for embedded C/C++"
summary: "Tips and trick for embedded C/C++"
date: 2020-06-13T19:01:19+02:00
highlight: true
---
# Set a bit
```c
// Set one bit high at position "bit" in input and store to output
output = input | (1 << bit);
// Shorthand
variable |= (1 << bit);
// Multiple bits
variable |= (0b101 << bit);
```
# Clear a bit
```c
// Clear one bit high at position "bit" in input and store to output
output = input & ~(1 << bit);
// Shorthand
variable &= ~(1 << bit);
// Multiple bits
variable &= ~(0b101 << bit);
```
# Toggle a bit
```c
// Clear one bit high at position "bit" in input and store to output
output = x ^ (1 << bit);
// Shorthand
variable ^= (1 << bit);
// Multiple bits
variable ^= (0b101 << bit);
```
# Math
```c
// Division using bitshift
output = input >> 1; // Divide by 2
output = input >> 2; // Divide by 4
output = input >> 3; // Divide by 8
// Multiply using bitshifting
output = input << 1; // Multiply by 2
output = input << 2; // Multiply by 4
output = input << 3; // Multiply by 8
```
# Set X number of bits high.
```c
output = (0b1 << X) -1;
```
# Miscellaneous
```c
// Check if number is ODD
if( (num & 1) == 1) {};
// Flip signed integer
num = ~num + 1;
// Power of two
num > 0 && (num & (num - 1)) == 0;
```