...

/

Discussion: Bits and Pieces

Discussion: Bits and Pieces

Execute the code to understand the output and gain insights into bitwise operator (~).

Run the code

Now, it's time to execute the code and observe the output.

#include <stdio.h>

int main()
{
  int a, b;
  printf("Enter an integer: ");
  scanf("%d", &a);
  b = ~a + 1;
  printf("Result: %d\n", b);

  return(0);
}
C code for the given puzzle

Understanding the output

The user types a value, and then the program outputs the negative for that value:

Enter an integer: 12345
Result: -12345
Code output

Changing the sign for an integer value is done by using binary manipulation, resetting the sign bit and adjusting the final value by one to equal the negative of the value input.

To understand this chapter’s code, you must know two things: first, how the computer stores signed integers, and second, how the two’s complement operator works at the binary level.

Signed integer

A signed integer uses the far-left bit, the sign bit, to indicate a positive or negative value. When the sign bit is zero (unset), the value is positive. When the sign bit is one (set), the value is negative. For example:

5 in binary is 0000 0101
-5 in binary is 1111 1011
Binary of 5 and -5 (8-bit)

You might think that 5-5 ...