Convert byte[] to sbyte[]
sbyte[] signed = (sbyte[]) (Array) unsigned;
This works because byte and sbyte have the same length in memory and can be converted without the need to alter the memory representation.
This method might, however, lead to some weird bugs with the debugger. If your byte array is not very big, you can use Array.ConvertAll
instead.
sbyte[] signed = Array.ConvertAll(unsigned, b => unchecked((sbyte)b));
How about using Buffer.BlockCopy
? The good thing about this answer is that avoids cast checking on a byte by byte basis. The bad thing about this answer is that avoids cast checking on a byte by byte basis.
var unsigned = new byte[] { 0x00, 0xFF, 0x1F, 0x8F, 0x80 };
var signed = new sbyte[unsigned.Length];
Buffer.BlockCopy(unsigned, 0, signed, 0, unsigned.Length);
This just copies the bytes, values above byte.MaxValue
will have a negative sbyte
value.
Takes two lines of code but should be quick.