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?
The range is
[-128, +127]indeed. The range[-127, +127]would mean thatsbytecan represent only255different values, while 8 bits make256combinations.And BTW if
-128would not be a legal value, compiler would complain aboutThere is no overload
Convert.ToString(sbyte value, int toBase), so in your caseConvert.ToString(int value, int toBase)is called, andsbyteis promoted toint.To quickly check the value, you can print
sbyteas a hexadecimal number:Sure,
sbyte.MaxValueis127, soi<=127is alwaystrue. Wheniis127and gets incremented, an overflow occurs and the next value is-128.