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!
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};
In Java, bytes are signed, and in C#, bytes are unsigned. You can convert from signed to unsigned by adding 256 to the number, so that (in your example) -32 becomes 224 and -3 becomes 253.
As Ichabod Clay says (in comments), you can also use the sbyte type so that you don't have to do that conversion. Personally I dislike signed bytes, so if this were for literal data, I'd just convert once and be done, but you have a choice. Yay. :-D
In general, you can simply cast the signed to unsigned and back again. Most of the time you are interested in the bit value of the bytes anyway. Those stay the same in both systems (because the way two-complement signed numbers have been defined). Now if you upcast to a value that uses more bits, and you want to convert to an unsigned positive number, just use a bitwise AND using a 1 bit for the number of bits that you require.
In C# you can use
int negInt = (sbyte) b;
byte anotherB = (byte) negInt;
and in Java use:
int posInt = b & 0xFF;
byte anotherB = (byte) posInt;
You can use such functionality when you require the value of the bytes as number. Otherwise you can just store the bits in a byte array - signed or unsigned.
This method should also work for the specification of an entire byte array - as you used in your C# example:
new byte[] {59, 55, 79, 1, 0, 64, (byte)-32, (byte)-3};
or even
new byte[] {(byte)59, (byte)55, (byte)79, (byte)1, (byte)0, (byte)64, (byte)-32, (byte)-3};
You may need to add unchecked() in case you are using C#.
The same goes for Java:
new byte[] { (byte) 255, etc. }
for this kind of conversion you may want to learn how to use regular expressions find/replace in your favorite editor.
In the end it requires a bit of playing around with casting and bitwise AND to get a feeling for it. Once you understand it will never leave you though.
new byte[]{59, 55, 79, 1, 0, 64, (byte)-32, (byte)-3};uncheckedoperator, as innew byte[] { 59, 55, 79, 1, 0, 64, unchecked((byte)-32), unchecked((byte)-3), }.