Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative numbers are stored as 2's complement in memory, how does the CPU know if it's negative or positive?

Tags:

-1 can be represented in 4 bit binary as (2's complement) 1111

15 is also represented as 1111.

So, how does CPU differentiate between 15 and -1 when it gets values from memory?

like image 743
MCG Avatar asked Oct 06 '11 22:10

MCG


People also ask

How do you recognize if a two's complement number is positive or negative?

With two's complement, the bit at the far left of the bit pattern - the most significant bit or MSB - is used to indicate positive or negative and the remaining bits are used to store the actual size of the number. Positive numbers always start with a 0.

Why are negative numbers stored in computers as 2's complement?

The big advantage of 2's complement for negative numbers is that you can do the easier addition when trying to substract one from another binary number. That's because with 2′complement, the Most Sigificant Bit (MSB) on the left reads as -2^n, while all other binary digits are positive.

How does the computer distinguish between positive and negative numbers?

Computers use the first bit to indicate this. If the first bit is 1 , the number is negative. If the first bit is 0 , the number is positive. To determine the value of the number, the other 7 bits are used.

How does a computer understand negative numbers?

In computing, signed number representations are required to encode negative numbers in binary number systems. In mathematics, negative numbers in any base are represented by prefixing them with a minus sign ("−").

How are negative numbers stored in a processor?

In most implementations that you are likely to encounter, negative signed integers are stored in what is called two's complement. The other major way of storing negative signed numbers is called one's complement. The one's complement of an N-bit number x is defined as x with all its bits flipped, basically.

How are negative integers stored on x86 CPU's?

in x86 processors, the sign is indicated by the Most Significant Bit. If the most significant bit is set to 1, that means the number is negative. If the MSB is set to 0, the number is positive.


1 Answers

The CPU doesn't care whether a byte holds -1 or 15 when it moves it from one place to another. There's no such thing as a "signed move" (to a location of the same size - there is a signed move for larger or smaller destinations).

The CPU only cares about the representation when it does arithmetic on the byte. The CPU knows whether to do signed or unsigned arithmetic according to the op-code that you (or the compiler on your behalf) chose.

like image 128
Peter vdL Avatar answered Nov 14 '22 00:11

Peter vdL