0

Some where I have studied that in a signed data type one bit is used for sign so in that case positive value is 127 in char type as one can write + 1111111 in binary form so in negative also it should take value -127 as -1111111 but it is -128 why?

  • You are describing a system called sign-and-magnitude. Most computers don't use that, they use two's-complement. – Mark Ransom Feb 02 '22 at 02:34
  • @HimanshuKumar Note that there should be 256 values in total. Now, if you count from `-127` to `127` you'll get `255`. On the other hand if you count from `-128` to `127` then you'll get exactly `256` values which is what we want. Also don't forget to include `0` while counting. – Jason Feb 02 '22 at 02:38
  • @HimanshuKumar Most computers(if not all) use two's complement form to store negative numbers. – Jason Feb 02 '22 at 02:43
  • 1
    In C++20, [2s-compliment is now required for signed integers](https://stackoverflow.com/questions/57363324/). – Remy Lebeau Feb 02 '22 at 02:49

1 Answers1

0

Let's create a simple table, a list of all numbers that can be expressed in two, instead eight bits. One bit is still used for the sign, and one bit for the actual value. If we do that, then this is the table that we'll end up with:

decimal binary
-2 10
-1 11
0 00
1 01

So, that's what you get with two-bit long numbers. Note that the smallest value is -2 and the largest is 1.

Now, let's move on to three bits:

decimal binary
-4 100
-3 101
-2 110
-1 111
0 000
1 001
2 010
3 011

The smallest representable value is -4, and the largest one is 3.

If you continue on with this process, when you arrive at 8-bit numbers you will find that the smallest value will be -128 and largest one will be 127.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148