0

As I remember we had learned that signed integer types (sbyte, short, int , long) the first bit is for the sign and the latter 7 bit is for the value.

I saw that sbyte range is -128 to 127 while I thought it must be -127 to 127.

I tried some codes to understand how this is possible and I faced two strange things:

1- I tried the following code:

sbyte a = -128;
Console.Write(Convert.ToString(a, 2));

and the resutl was

1111111100000000

As if its a two byte variable.

2-Tried converting all numbers in the range to binary:

for(sbyte i=-128;i<=127;i++)
{
    Console.WriteLine(Convert.ToString(i, 2));
    if(i==127) break;
}

If I omit the if(i==127) break; the loop goes on. and with the break, the code in the loop does not execute, some how as if -128 is greater than 127.

My Conclusion: As I thought that -128 must not fit in a unsigned byte variable and the first and second tries approves that (111111110000000 > 01111111) but If it does not fit, then why range is -128 to 127?

Ashkan Mobayen Khiabani
  • 30,915
  • 26
  • 90
  • 147

1 Answers1

3

I saw that sbyte range is -128 to 127 while I thought it must be -127 to 127.

The range is [-128, +127] indeed. The range [-127, +127] would mean that sbyte can represent only 255 different values, while 8 bits make 256 combinations.

And BTW if -128 would not be a legal value, compiler would complain about

sbyte a = -128;

There is no overload Convert.ToString(sbyte value, int toBase), so in your case Convert.ToString(int value, int toBase) is called, and sbyte is promoted to int.

To quickly check the value, you can print sbyte as a hexadecimal number:

sbyte s = -1;
Console.WriteLine("{0:X}", s); // FF, i.e. 11111111

If I omit the if(i==127) break; the loop goes on.

Sure, sbyte.MaxValue is 127, so i<=127 is always true. When i is 127 and gets incremented, an overflow occurs and the next value is -128.

AlexD
  • 30,405
  • 3
  • 66
  • 62