I tried to convert an Array from byte[]
to sbyte[]
.
Here is my sample Array:
byte[] unsigned = { 0x00, 0xFF, 0x1F, 0x8F, 0x80 };
I already tried this:
sbyte[] signed = (sbyte[])((Array)unsigned);
But it doesn't work. There is no value in the array after this operation.
Does anybody has an better idea?
In C#, the sbyte and sbyte data types, used for byte type data. While byte is used to store unsigned byte data, which works only on positive values from 0–255 , sbyte works on both negative and positive between -128 and 127 .
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.
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));
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