I’m a self-made programmer, therefore I don’t know much about bits and bytes and hexadecimal values.
One of the libraries I use receives data from a remote service as byte array. I have found a method to convert this byte array data:
public string ByteArrayToHexString(byte[] buf)
{
if (buf == null) return "";
StringBuilder sb = new StringBuilder(buf.Length * 2 + 2);
for (int i = 0; i < buf.Length; i++)
{
sb.Append(buf[i].ToString("x2"));
}
return sb.ToString();
}
Using this method I get strings like these:
0031
or
0022
or
002d
Are those actual values sent by the service or should further conversion required? What should I do to get the actual values?
I’m going to make no attempt to answer the question as to what your byte values mean, or whether they are “correct”, because we have no way of knowing, given the information presented here. Instead I’m going to take you through your conversion, step by step, to answer your question “Are those actual values sent by the service?”
A
byte[]is an array of bytes – a “byte array”.An array is a fixed size set of values.
A
byteobject in C# is a value whose range falls between the decimal numbers 0 and 255.So a “byte array” is literally just a bunch of numbers, in order, all of which are between 0 and 255.
Hexadecimal values are just one way to visualise a byte array.
(And for complete clarity, hexadecimal is base 16, decimal is base 10.)
The numbers in the columns below are equivalent.
So imagine an array of bytes with the following decimal values:
That’s equivalent to an array of bytes with the following hexadecimal values:
That can also be written as:
or more commonly:
or:
or:
So if your service is returning a byte array and you’re seeing values like
002d, that means, you received two bytes, first byte is 0 (0 is the same in base 10 and base 16), second byte is 2d (hex) which can also be expressed as 45 in decimal (base 10).Short answer, notwithstanding anything you’ve not told us, yes, those hexadecimal values do represent the actual values received from the service.