Is 2s complement a way to store negative number?

一笑奈何 提交于 2020-02-04 10:44:21

问题


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:


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




回答2:


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)



来源:https://stackoverflow.com/questions/28233888/is-2s-complement-a-way-to-store-negative-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!