In Java I have the following line:
new byte[]{59, 55, 79, 1, 0, 64, -32, -3};
However, in C# I can't use negative bytes in a byte array. I tried casting it to byte and it failed. What can I do? thanks!
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 .
Negative Numbers.Because Byte is an unsigned type, it cannot represent a negative number. If you use the unary minus ( - ) operator on an expression that evaluates to type Byte , Visual Basic converts the expression to Short first.
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 ).
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
Because in C# bytes are unsigned. In Java, bytes are signed.
From Byte Structure
Byte is an immutable value type that represents unsigned integers with values that range from 0 (which is represented by the Byte.MinValue constant) to 255 (which is represented by the Byte.MaxValue constant)
From Primitive Data Types
The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127
What can I do?
You can use sbyte
in C# which represents 8-bit signed integer.
The SByte value type represents integers with values ranging from negative 128 to positive 127.
Like;
sbyte[] sb = new sbyte[] {59, 55, 79, 1, 0, 64, -32, -3};
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