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?
In Java, byte is an 8-bit signed (positive and negative) data type, values from -128 (-2^7) to 127 (2^7-1) . For unsigned byte , the allowed values are from 0 to 255 .
A byte is an unsigned char. Unsigned means has no sign, can't be negative. Use char. The question is only stupid because there is no code to demonstrate how you store a negative value in an unsigned variable (which byte is).
In most implementations that you are likely to encounter, negative signed integers are stored in what is called two's complement. The other major way of storing negative signed numbers is called one's complement. The one's complement of an N-bit number x is defined as x with all its bits flipped, basically.
Negative integers are stored as the two's complement of their absolute value. The two's complement of a positive number is when using this notation a negative number.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With