简体   繁体   中英

Representation of negative numbers in binary

I am styding about the different data types in C. In my book it is written that the signed char data type is of 1 byte(8 bits) . Now,it is written that the range of ASCII codes that can be stored in signed char data type is from -128 to 127 .

It was written that a negative number is stored as a 2's complement of its binary.

I can't understand how is it possible to store the 2's complement form of -128 within 8 bits ?

First of all we need 9 bits to write the signed binary representation of +128 which is 010000000 .Now, if we take the 2's complement form of it, we get 110000000 which is also 9 bits long. Then how are we able to store -128 in a 8 bit signed char ?

You can store -128 as 1000 0000.

The first 1 indicates that you are using a negative number and then, how I learned it, you count the 0's as if they are 1's and vice versa and at the end you add 1. This means that for your case you would perform the following steps (when the first digit is a 1):

  1. Take the signed char: 1000 0000.
  2. Strip the first digit and switch the other digits: 111 1111.
  3. Calculate, in 'simple' binary the value: in this case 127.
  4. Add 1 and afterwards add negative sign: -128.

It is important that you take into account that all negative numbers are counted 'inversed':

  • -1 in decimal is written as 1111 1111
  • -2 in decimal is written as 1111 1110
  • -3 in decimal is written as 1111 1101
  • -4 in decimal is written as 1111 1100
  • etc.

This means that you have 128 possible values, but since you do not have to include the decimal 0 (because it is represented as 0000 0000), your negative range is [-1, -128], while on the other hand the range is [0, 127].

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