0
0
Embedded Cprogramming~5 mins

NOT for inverting bits in Embedded C

Choose your learning style9 modes available
Introduction

The NOT operator flips each bit in a number from 0 to 1 or from 1 to 0. It is used to invert bits in embedded C programming.

When you want to toggle all bits of a byte or integer.
When you need to create a mask that selects bits not set in another mask.
When you want to quickly invert a binary pattern for hardware control.
When implementing bitwise operations for flags or settings.
Syntax
Embedded C
~variable_or_value

The tilde (~) symbol is the NOT operator in C.

It works on each bit individually, flipping 0 to 1 and 1 to 0.

Examples
Here, ~a flips all bits of a.
Embedded C
unsigned char a = 0b00001111;
unsigned char b = ~a;  // b becomes 0b11110000
NOT flips all bits including sign bit, so y is negative in two's complement.
Embedded C
int x = 5;  // binary 00000000 00000000 00000000 00000101
int y = ~x;  // y becomes binary 11111111 11111111 11111111 11111010
Sample Program

This program shows how the NOT operator flips bits of an 8-bit value.

Embedded C
#include <stdio.h>

int main() {
    unsigned char val = 0b10101010;
    unsigned char inverted = ~val;
    printf("Original: 0x%X\n", val);
    printf("Inverted: 0x%X\n", inverted);
    return 0;
}
OutputSuccess
Important Notes

Remember that the NOT operator flips all bits, including unused bits in larger types.

For signed integers, the result may be negative due to two's complement representation.

Use unsigned types to avoid confusion when working with bitwise NOT.

Summary

The NOT operator (~) flips every bit in a number.

It is useful for inverting bits in embedded systems.

Use unsigned types to clearly see bit inversion results.