Convert byte [] to array

Please check this code

float f = BitConverter.ToSingle(new byte[] { 0xBF, 0x04, 0x8E, 0xFF }, 0);
byte[] b = BitConverter.GetBytes(f);

this causes a strange result. b will be {0xBF, 0x04, 0xCE, 0xFF}

I assume this is because the value of f is NaN. the reason I ask this question is because I use Marsal to convert the byte stream to a structure containing float, I swap endianity

The fact is that when I get to the field it's already messed up (as in the above example)

any ideas?

Thanks!

+4
source share
2 answers

, , NaN , , , :

byte[] input = { 0xBF, 0x04, 0x8E, 0xFF };
bool reversed = false;
float f = BitConverter.ToSingle(input, 0);

if (float.IsNaN(f))
{
    reversed = true;
    f = BitConverter.ToSingle(input.Reverse().ToArray(), 0);
}

byte[] b = BitConverter.GetBytes(f);

if (reversed)
    b = b.Reverse().ToArray();
+2

:

double f = BitConverter.ToDouble(new byte[] { 0, 0, 0, 0, 0xBF, 0x04, 0x8E, 0xFF }, 0);
byte[] b = BitConverter.GetBytes(f);

:

int f = BitConverter.ToInt32(new byte[] { 0xBF, 0x04, 0x8E, 0xFF }, 0);
byte[] b = BitConverter.GetBytes(f);

, . ({ 0xBF, 0x04, [0x8E to 0xBE] , 0xFF } - +4 'd .

4 Int32, .

0

All Articles