GetBytes with an argument of type sbyte

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

byte[] byteArray = BitConverter.GetBytes((sbyte)127)
+4
source share
1 answer

GetBytesdoes not have an overload that accepts sbyte, so your sbyteimplicitly converts to shortand you call GetBytes(short), which returns two bytes.

You should just translate sbyteto bytes unchecked.

sbyte s = 127;
byte[] byteArray = new[] { (byte)s };
+5
source

Source: https://habr.com/ru/post/1540250/


All Articles