Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetBytes with argument of sbyte type

Tags:

c#

Why GetBytes returns array of two elements instead of array of one element, although storage of sbyte takes only 1 byte.

byte[] byteArray = BitConverter.GetBytes((sbyte)127)
like image 795
user2734153 Avatar asked May 12 '14 15:05

user2734153


1 Answers

GetBytes does not have an overload that takes an sbyte, so your sbyte is being implicitly converted to short and you call GetBytes(short), which returns two bytes.

You should simply cast your sbyte to a byte with unchecked conversion.

sbyte s = 127;
byte[] byteArray = new[] { (byte)s };
like image 159
Tim S. Avatar answered Sep 27 '22 02:09

Tim S.