1
$\begingroup$

I am taking a class in computer science and I am not sure about the following. When one transforms $247_{10}$ into its binary counterpart one gets $11110111_2$. However, the same binary number corresponds also to$-9$ when the 2-complement representation is considered. How does the computer know which of the two numbers we mean, or eventually how one can know which of the two numbers is meant ? If we provide to the machine $-9$ it is then clear how to proceed to get the binary, but after a certain number of arithmetic if the computer gets as a result $11110111$ how it will make it to provide the correct decimal number, i.e. 247 versus -9 ? Thanks.

$\endgroup$
2
  • $\begingroup$ How does the computer know [what] we mean. It does not, and doesn't need to - just follow instructions. $\endgroup$
    – greybeard
    Commented Sep 20, 2022 at 4:41
  • $\begingroup$ The type of the data in memory is implied by the program that refers to it. $11110111$ could be taken for the numbers $-9$ or $243$, for the character $\le$ or yet other interpretations, depending on how the data has been declared. The type is not attached explicitly to the bytes. $\endgroup$
    – user16034
    Commented Sep 20, 2022 at 11:34

1 Answer 1

1
$\begingroup$

As far as a CPU is concerned, everything is bits/bytes/words in memory. It doesn't "know" what the contents of a memory location means.

CPUs do have instructions that operate differently on (say) signed and unsigned integers. For example, it might have separate instructions for:

  • Signed vs unsigned multiplication.
  • Sign extension vs zero extension, when loading (say) a byte into a register.
  • Signed vs unsigned trapping addition/subtraction. Trapping arithmetic causes a trap/exception if the operation overflows or underflows. For integer addition and subtraction, if trapping is not desired, then there is no reason to distinguish between signed and unsigned arithmetic, which, as you probably know, is the main advantage of two's complement.

It's up to the programmer to decide which instruction to use on which memory location.

If you're not programming in assembly, this is handled by your language's type system, where instead of programming with memory locations and registers, you program with variables and types. Different languages have different variable semantics, but either way, the language implementation knows whether a variable is signed or unsigned, and issues the appropriate CPU instruction accordingly.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.