I'm using BitConverter.GetBytes()
to convert various variables (of different types) to a byte array, to pass it to a custom method where I need to check the value of each byte.
I've noticed that I can pass a variable of type byte
to BitConverter.GetBytes()
(even if it is not listed in the Overload list: see related MSDN page) and in this case I always have a 2-bytes array as return value.
Shouldn't I have a single-byte array as return value? How does .NET interpret the byte argument?
Sample:
byte arg = 0x00;
byte[] byteArr = BitConverter.GetBytes(arg);
// Result: byteArr is a 2-bytes array where byte[0] = 0 and byte[ 1] = 0
The use of BitConverter Class is to convert a base data types to an array of bytes and an array of bytes to base data types. This class is defined under System namespace. This class provides different types of methods to perform the conversion.
An int value can be converted into bytes by using the method int. to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution.
When you look up GetBytes() you will find that there is no overload that takes a byte
parameter.
You are looking at the results of the closest match, GetBytes(Int16)
and that of course produces a byte[2]
.
In other words, your code:
byte arg = 0x00;
byte[] byteArr = BitConverter.GetBytes(arg);
is equivalent to:
byte arg = 0x00;
short _temp = arg;
byte[] byteArr = BitConverter.GetBytes(_temp);
As the other answers have pointed out, there is no GetBytes overload that takes a byte parameter. The next question is why does it choose the overload that takes a short. It could pick any of these for example:
GetBytes(short)
GetBytes(int)
GetBytes(long)
GetBytes(float)
...
The reasoning for why it chooses short is not just because short is the next closest thing. There is better reasoning behind it. The C# language specification explains:
"Given an implicit conversion C1 that converts from a type S to a type T1, and an implicit conversion C2 that converts from a type S to a type T2, the better conversion of the two conversions is determined as follows" [1]
Here are two possible conversions from S to either T1 or T2:
S
C1 byte short (T1)
C2 byte int (T2)
The rule that works here is:
"If an implicit conversion from T1 to T2 exists, and no implicit conversion from T2 to T1 exists, C1 is the better conversion."
There's is an implicit conversion from short to int, but not from int to short, so the conversion from byte to short is chosen.
[1] http://msdn.microsoft.com/en-us/library/aa691339(v=vs.71).aspx (old copy)
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