0

I understand that an sbyte foregoes a bit in order to "sign" it's value, positive or negative. This naturally leaves 7 bits for the value being 72 = 128 (0 to 127 OR -1 to -128 dependent on the signing bit).

My question is, which of the 8 bits in the byte is the signing bit? I imagine it to be bit 8, the MSB?

I ask since I would of expected byte foo = -1 to explicitly cast to 129 with byte bar = (byte)foo since the underlying bit structure would be 10000001. However, the above returns bar as 255.

Test Code

    sbyte negative = -1;
    sbyte postive = 1;

    byte negativeResult = (byte)(negative & 0b_1000_0001);
    byte positiveResult = (byte)(postive & 0b_1000_0001);

    Console.WriteLine($"Negative evaluated to: {Convert.ToString(negativeResult, toBase: 2)}");
    Console.WriteLine($"Positive evaluated to: {Convert.ToString(positiveResult, toBase: 2)}");

Output

    Negative evaluated to: 10000001
    Positive evaluated to: 1
George Kerwood
  • 1,248
  • 8
  • 19
  • 2
    Does this answer your question? [What is “2's Complement”?](https://stackoverflow.com/questions/1049722/what-is-2s-complement) It is the top bit, but it doesn't work the way you expect. – harold Nov 15 '20 at 10:48
  • The leftmost digit (bit). 0 for positive, 1 for negative. – Júlio César Schincariol Filho Nov 15 '20 at 10:49
  • @harold Thank you, Sir. I hadn't heard the expression "complement" before and I certainly hadn't imagined it to work that way, very interesting! – George Kerwood Nov 15 '20 at 10:51
  • 1
    @GeorgeKerwood one way you can look at "why does -1 cast to 255", is to ask what should happen when you add 1 to it. You should get zero as the result, right? `(byte)(255+1)` is also zero, in that sense -1 and 255 are just different ways to look at the same thing (all bits set). – harold Nov 15 '20 at 10:55
  • @harold. If I've understood correctly therefore, this is exactly why `sbyte -1` casts to `byte 255`, since the bit pattern is maintained as `11111111`? – George Kerwood Nov 15 '20 at 10:55
  • @harold, yup yup, got it now! Awesome, thanks again. – George Kerwood Nov 15 '20 at 10:56

0 Answers0