How does the computer recognise that a a given number is in its Two's comeplent form?

不羁岁月 提交于 2020-01-07 03:36:09

问题


I understand what the Two's complement is and what it is useful for. What I'd like to know is how does the computer decide that the number is in its Two's complement form?

How and when does it decide that 1111 1110 is -2 and not 254? Is it at the OS level of processing?


回答1:


The computer will already be expecting the data to be in (or not in) two's complement form (otherwise there wouldn't be a way of telling if it is - 2 or 254). And yes, that would probably be decided at the OS-level.

You can probably relate this to the same kind of idea used when setting variable types when declaring variables in a high-level programming language; you'll more than likely set the type to be "decimal", for example, or "integer" and then the compiler will expect values to stick to this type.




回答2:


As far as I think it is dependable on programming language.

Lets say integer allocates 1 byte of memory (to make it simple).

If it is UNSIGNED integer (only positive numbers) you can use any number from 0 to 255 (in total of 2^8 numbers, zero included).

00000000 would be 0, and 11111111 would be 255 decimal.

But if your integer is SIGNED ( u can use both, negative and positive numbers) you can use values from -127 to 127, zero included (again 2^8 numbers).

If your compiler bumps into 11111111 SIGNED int value, it will not interpret it as 255 because signed int allows only values from 0 to 127 for positive numbers so it will take it as -1. Next one, -2 would be 11111110 (254 decimal) and so on...



来源:https://stackoverflow.com/questions/34795902/how-does-the-computer-recognise-that-a-a-given-number-is-in-its-twos-comeplent

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