简体   繁体   中英

Is 2s complement a way to store negative number?

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):

What is “2's Complement”?

Why is two's complement used to represent negative numbers?

http://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html

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"...)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM