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

14,293

Solution 1

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)

Solution 2

In C#, a byte represents an unsigned 8-bit integer, and can therefore not hold a negative value (valid values range from 0 to 255). An alternative is sbyte, which is a signed 8-bit integer (valid values from -128 to 127).

Share:
14,293
user2077725
Author by

user2077725

Updated on June 05, 2022

Comments

  • user2077725
    user2077725 about 2 years

    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?

  • Jeppe Stig Nielsen
    Jeppe Stig Nielsen over 11 years
    To supplement, you can of course also force the cast to happen. This is done like so (when buffer is a byte[]): buffer[index] = unchecked((byte)(-128)); The unchecked(...) part can be left out when two conditions are met: 1: The value to be cast is not a compile-time constant, and 2: The code is not compiled with /checked compiler option. So in these cases you would just say buffer[index] = (byte)nonConstant;.