Why can I not store a negative value in a byte variable?

byte, c#

Solution

The `byte` data type in Java is signed (-128–127). The equivalent data type in C# is `sbyte`.

So the equivalent C# code is as follows:

sbyte[] buffer = new sbyte[64];
buffer[..] = -128;

If you want an array of unsigned bytes (0–255), the `byte` with the same bit pattern as the `sbyte` -128 is 128 (0x80).

byte[] buffer = new byte[64];
buffer[..] = 128;

See also: Integral Types Table (C# Reference)

Problem

I am converting code that works in Java but not in C# ``` byte[] buffer = new byte[64]; this.buffer[((int)this.count & 0x3F)] = -128; ``` This generates a compile time error "Constant value '-128' cannot be converted to a 'byte'." How can I store a negative number for a byte?

Original source