简体   繁体   English

浮点到字节数组转换

[英]Float to byte array conversion

We use 我们用

float f= 3.5f ;
BitConverter.GetBytes(f);

It returns byte array of length 4. But I wonder the math behind this. 它返回长度为4的字节数组。但是我不知道其背后的数学原理。 Anyone will teach the math behind this conversion? 有人会教这种转换背后的数学吗? Also double conversion info is appreciated. 还赞赏双重转换信息。

Under the covers, it is using unsafe, C-style pointers to copy the underlying 32-bit value into a 32-bit array (a byte[4] ): 在幕后,它使用不安全的C风格指针将基础的32位值复制到32位数组( byte[4] )中:

int rawBits = *(int*)&value;
byte[] bytes = new byte[4];
fixed(byte* b = bytes)
    *((int*)b) = rawBits;
return bytes;

The results are architecture dependent, insofar as the order of the bytes matches the memory byte order (endianness) of the machine where the copy took place. 结果取决于体系结构,只要字节顺序与发生复制的机器的内存字节顺序(字节序)相匹配即可。

For example, if the 32-bit rawBits value is 0xAABBCCDD , and it is represented in memory as AA BB CC DD , then the array will contain 0xAA, 0xBB, 0xCC, 0xDD . 例如,如果32位rawBits值为0xAABBCCDD ,并且在内存中以AA BB CC DD ,则该数组将包含0xAA, 0xBB, 0xCC, 0xDD If the in-memory representation was DD CC BB AA , then the array will contain 0xDD, 0xCC, 0xBB, 0xAA . 如果内存中表示形式为DD CC BB AA ,则该数组将包含0xDD, 0xCC, 0xBB, 0xAA

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

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