Reputation: 1105
I have read many articles and SO answers to understand 2s complement
. They have helped me a lot. However, there are few doubts in my mind about 2s complement
.
1) Is 2s complement
a way to store negative numbers in order to make operation easy or have some other applications too?
2) 2s complement
is taken automatically when computer see a negative number?
3) Taking 2s complement
is -- compiler's job or done by processor or what?
4) When 2s complement
is taken at -- compile time, run time or at the time of assiging a value to a variable?
Articles I read are (should recommend to understand 2s complement
better):
Why is two's complement used to represent negative numbers?
http://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html
Upvotes: 3
Views: 1116
Reputation: 213842
1) Yes.
2) The computer can't "see" a negative number. It can see a chunk of binary data. Your application is what possesses the intelligence to say "this chunk of binary data is an integer stored in 2's compl". However, almost every CPU in the world has support for 2's complement arithmetic.
3) The compiler sees the source code such as int32_t x = 0;
and then realizes that this variable is stored in two's complement format. If you then add code like x = x - 1
the compiler chooses to use processor instructions that support 2's complement, when it generates your program. The processor only does what the program tells it to do. It has no intelligence.
4) As described above, it is a compile-time decision. (Not really sure what you mean with "complement taken"...)
Upvotes: 3
Reputation: 30489
Is 2s complement a way to store negative numbers in order to make operation easy?
Yes it is one of the way to store signed number (negative and positive numerals, not just negative)
2s complement is taken automatically when computer see a negative number?
Again negative -> signed. Depends on the architecture. One may choose 1s, 2s or some other representation.
Taking 2s complement is -- compiler's job or done by processor or what?
Compiler must understand the system and processor may or may not understand the 2s complement system.
When 2s complement is taken at -- compile time, run time or at the time of assiging a value to a variable?
2s complement may be calculated at all stages (compile, run)
Upvotes: 2