2020-06-25 22:43:14 +02:00
|
|
|
---
|
|
|
|
title: "Bit magic in C (and C++)"
|
2020-08-02 14:48:01 +02:00
|
|
|
subtitle: "Tips and trick for embedded C/C++"
|
2020-08-02 14:44:30 +02:00
|
|
|
summary: "Tips and trick for embedded C/C++"
|
2020-06-25 22:43:14 +02:00
|
|
|
date: 2020-06-13T19:01:19+02:00
|
2021-05-03 16:15:05 +02:00
|
|
|
highlight: true
|
2021-07-28 14:42:22 +02:00
|
|
|
math: true
|
2020-06-25 22:43:14 +02:00
|
|
|
---
|
|
|
|
|
|
|
|
# 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);
|
2020-07-05 11:14:47 +02:00
|
|
|
// Multiple bits
|
|
|
|
variable |= (0b101 << bit);
|
2020-06-25 22:43:14 +02:00
|
|
|
```
|
|
|
|
|
|
|
|
# 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);
|
2020-07-05 11:14:47 +02:00
|
|
|
// Multiple bits
|
|
|
|
variable &= ~(0b101 << bit);
|
2020-06-25 22:43:14 +02:00
|
|
|
```
|
|
|
|
|
|
|
|
# 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);
|
2020-07-05 11:14:47 +02:00
|
|
|
// Multiple bits
|
|
|
|
variable ^= (0b101 << bit);
|
2020-08-02 14:34:35 +02:00
|
|
|
```
|
|
|
|
|
|
|
|
# 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;
|
|
|
|
```
|
|
|
|
|
2021-07-28 14:42:22 +02:00
|
|
|
# Minimum required bits
|
|
|
|
$$bits = { log(number) \over log(2) }$$
|
|
|
|
Since you can not use fractions of a bit the number should be rounded up.
|
|
|
|
|
2020-08-02 14:44:30 +02:00
|
|
|
# Miscellaneous
|
2020-08-02 14:34:35 +02:00
|
|
|
```c
|
|
|
|
// Check if number is ODD
|
|
|
|
if( (num & 1) == 1) {};
|
|
|
|
// Flip signed integer
|
|
|
|
num = ~num + 1;
|
2021-07-28 14:42:22 +02:00
|
|
|
// Is an integer a power of two?
|
2020-08-02 14:34:35 +02:00
|
|
|
num > 0 && (num & (num - 1)) == 0;
|
2021-07-28 14:42:22 +02:00
|
|
|
//Clear all bits from 0 to N
|
|
|
|
mask = ~((1 << n+1 ) - 1);
|
|
|
|
x &= mask;
|
|
|
|
|
|
|
|
|
2020-06-25 22:43:14 +02:00
|
|
|
```
|