Negative numbers as binary code - how it works
Related Videos: Twos complement: Negative numbers in binary (May 2024).
Negative numbers are often used when programming. This practical tip shows you how you can also represent these numbers as binary code.
Display negative numbers as binary code
The first bit is usually used as a sign to represent negative numbers. The 1 stands for a negative number. The number 42 is the number 101010 in the dual system. The number +42 is therefore represented in the dual system with 00101010, and the number -42 with 10101010.
- So that you can also count on this number, there is the so-called one's complement. The amount of a negative number is converted into a binary number, and then the complement is formed: -3 → | -3 | = (0011) ₂ → (1100) ₂
- The problem with one's complement is, however, the double representation of zero, i.e. 1111 and 0000. In addition, additions beyond zero do not work: -3 +5 ≠ 2
- So that you can also count with negative numbers, there is the two's complement in computer science. The double representation of the zero is avoided by adding a 1 before the conversion: -3 → | -3 + 1 | = (0010) ₂ → (1101) ₂
- If you add the number (1101) ₂ and 5 in writing, you will get 2 as the result.
Tricky riddle: This code comes from the secret service - can you solve it?
In the next practical tip, we will show you how you can decrypt a QR code by hand.