How are negative numbers stored in "hard" memory when they are encountered during compilation?

385 Views Asked by At

I am in the process of learning C/C++, so for some this might be a basic question but it is confusing to me.

Beautiful answers are given here related to how we interpret positive and negative numbers and how they look like in-memory (RAM memory) when the program is executing.

What I am thinking now is how are negative numbers stored in a compiled exec binary file; that is, when the program is not executing (not in a RAM memory). In other words, how are negative numbers after compiling stored on hardware hard disk (so when the program is not executing).

Will the compiler, when sees a negative number, for example int number = -25, first convert it to the 2's complement (1110 0111) and then store it in exec binary file (hard disk), or will it store it only as 25 with the highest bit set to 1 (1001 1001), and later when the execution of the program starts and when it sees that the most significant bit is 1, it will first convert it to the 2's complement (1110 0111), then load it into RAM (allocate memory, whatever) and start execution?

1

There are 1 best solutions below

7
Miles Budnek On

This isn't specified by the language. The compiler is free to do anything it wants so long as the behavior of the resulting program matches the behavior of the code you typed.

There are two common approaches that compilers take:

  1. Store the number as two's complement (or whatever format the CPU works with) in the executable file.
  2. Encode the number directly into immediate arguments to CPU instructions.

There's not really any reason to store numbers in a different format on disk and then do a conversion. That would just waste CPU cycles unnecessarily. When the OS's program loader loads an executable file, it copies various parts directly into various parts of memory. If all of the program's numeric constants aren't already in the format that the CPU works with, then the program would have to do a conversion before using them. That wastes time for no benefit.