简体   繁体   English

将byte []转换为数组问题

[英]Converting byte[] to array issue

Please check this code 请检查此代码

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

this yeilds a strange result. 这是一个奇怪的结果。 b will be { 0xBF, 0x04, 0xCE, 0xFF } b将是{0xBF,0x04,0xCE,0xFF}

I guess it is because the value of f is NaN. 我想这是因为f的值是NaN。 the reason I'm asking this question is because I use Marsal to convert a stream of bytes into a struct that contains a float, the I swap endianity 我问这个问题的原因是因为我使用Marsal将字节流转换为包含float的结构,I swap endianity

The thing is when I get to the field is already messed up (like the above example) 事情就是当我到达现场时已经搞砸了(就像上面的例子一样)

any ideas? 有任何想法吗?

Thanks! 谢谢!

Since your problem appears to an endian one, I'm wondering if checking for NaN and reversing the order and setting a boolean to reverse it back if necessary, would help: 由于您的问题出现在endian中,我想知道是否检查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();

This works: 这有效:

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

This one also does: 这个也做:

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

I believe the reason is in the single floating-point storage. 我相信原因在于单浮点存储。 The third byte ( { 0xBF, 0x04, [0x8E to 0xBE] , 0xFF } is being +4 'd for some reason while converted. 第三个字节( { 0xBF, 0x04, [0x8E to 0xBE] , 0xFF }由于某种原因在转换时为+4 { 0xBF, 0x04, [0x8E to 0xBE] , 0xFF }

The good containter for 4 bytes is Int32 and I advise you to use it. 4字节的好内容是Int32 ,我建议你使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM