- Home /
ByteArray impossible to convert... ?
PS : (My post is a picture because I have :''This post is currently awaiting moderation. contact a system administrator.'' everytime ... I guess it is the fault of number.)
Answer by Bunny83 · Dec 16, 2018 at 11:39 PM
Well, there are several things unclear which you have to clear up first:
What exact format are those values in.
What endianess does your system use.
To be the values look right if we assume that the first 4 bytes form a 32 bit integer in big endian format and the second value is a IEEE754 single floating point format, also in big endian. You have shown the byte values as decimal numbers but it makes more sense to show them in hexadecimal since it makes it easier to arrange them as a single number
0, 48, 0, 3 is just 00, 30, 00, 03 in hex. Since the bytes are in big endian the first byte is the most significant byte so the whole number is just 0x00300003. This is equivalent to the decimal number "3145731".
Likewise the decimal bytes 63, 83, 91, 53 are in hex 3F, 53, 5B, 35 or written as a single 32 number 0x3F535B35. By quickly using the IEEE754 online converter we can verify that this binary representation does indeed represent a floating point number that is equal to "0.82561046"
To convert this byte array in C# there are several ways to do this. The easiest way is to use the BitConverter class. However you have to adjust the order of the bytes depending on the system you are on. Usually all windows based desktop systems use little endian. Since your values are in big endian you would need to reverse the byte order of the 4 bytes which make up one value. If you are on a Mac or any other system that uses big endian you should be able to use the BitConverter right away.
For example
// big endian system
byte[] bytes;
int intVal = System.BitConverter.ToInt32(bytes, 0);
float fVal = System.BitConverter.ToSingle(bytes, 4);
// little endian system
void SwapBytes(bytes[] aBytes, int aIndex)
{
var b0 = aBytes[aIndex + 0];
var b1 = aBytes[aIndex + 1];
var b2 = aBytes[aIndex + 2];
var b3 = aBytes[aIndex + 3];
aBytes[aIndex + 0] = b3;
aBytes[aIndex + 1] = b2;
aBytes[aIndex + 2] = b1;
aBytes[aIndex + 3] = b0;
}
// [ ... ]
byte[] bytes;
SwapBytes(bytes, 0);
int intVal = System.BitConverter.ToInt32(bytes, 0);
SwapBytes(bytes, 4);
float fVal = System.BitConverter.ToSingle(bytes, 4);