Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

byte

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?

like image 286
user2077725 Avatar asked Feb 18 '13 15:02

user2077725


People also ask

Can a byte be negative Java?

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 .

Can a byte be negative Arduino?

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).

How can we store a negative integer?

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.

How are negative numbers stored in Java?

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.


1 Answers

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).

like image 108
John Willemse Avatar answered Nov 03 '22 01:11

John Willemse