Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java code - negative byte in byte array to C#

Tags:

c#

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!

like image 290
user2714359 Avatar asked Aug 25 '13 12:08

user2714359


People also ask

Can Java Bytes be negative?

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 you assign negative values to byte data type?

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.

Can byte hold negative values?

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

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.


1 Answers

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};
like image 164
Soner Gönül Avatar answered Oct 13 '22 11:10

Soner Gönül