Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert byte[] to sbyte[]

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?

like image 465
REMberry Avatar asked Sep 10 '14 07:09

REMberry


People also ask

What is a Sbyte in C#?

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 .


2 Answers

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.

like image 174
Jodrell Avatar answered Sep 19 '22 08:09

Jodrell


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));
like image 43
Simon Farshid Avatar answered Sep 22 '22 08:09

Simon Farshid