Explain how the bitwise NOT operator (~) works and provide an example.

Quick Overview

Explain how the bitwise NOT operator flips the bits of an integer and work through an example in a fixed width. Tests two's complement, why the result of NOT on a positive number is negative, and how signed, unsigned and Python integers differ.

Explain how the bitwise NOT operator (~) works and provide an example.

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: easy

Interview Round: Other

Explain how the bitwise NOT operator (`~`) works and provide an example. The result of `~` on a small positive number often surprises people, so be ready to explain why it comes out the way it does. ```hint Fix a width Write the number in a fixed width such as 8 bits, flip the bits, and then read the result as a two's complement value. ``` ### What a Strong Answer Covers - What NOT does to each bit, and that it takes a single operand. - A worked example in a fixed width, with the result read as a two's complement number. - The general relationship between `~x` and `-x` for signed integers, and why it holds. - How the result differs for unsigned types and in Python, and how to get an unsigned result there. - At least one common use, such as clearing bits with a mask. ### Follow-up Questions - Why is `~x + 1` equal to `-x` in two's complement? - In Python, how would you compute the 32-bit unsigned NOT of x? - In C, why does applying `~` to an `unsigned char` holding 5 not give 250?

Overview: Explain how the bitwise NOT operator flips the bits of an integer and work through an example in a fixed width. Tests two's complement, why the result of NOT on a positive number is negative, and how signed, unsigned and Python integers differ.

PracHub logo
General
Nov 25, 2026
easySoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Explain how the bitwise NOT operator (~) works and provide an example.

The result of ~ on a small positive number often surprises people, so be ready to explain why it comes out the way it does.

What a Strong Answer Covers Guidance

  • What NOT does to each bit, and that it takes a single operand.
  • A worked example in a fixed width, with the result read as a two's complement number.
  • The general relationship between ~x and -x for signed integers, and why it holds.
  • How the result differs for unsigned types and in Python, and how to get an unsigned result there.
  • At least one common use, such as clearing bits with a mask.

Follow-up Questions Guidance

  • Why is ~x + 1 equal to -x in two's complement?
  • In Python, how would you compute the 32-bit unsigned NOT of x?
  • In C, why does applying ~ to an unsigned char holding 5 not give 250?