【发布时间】:2019-11-22 11:26:34
【问题描述】:
我正在尝试查看System.Single 值在内存中的表示方式。
根据我的阅读,System.Single 表示如下:
1 个符号位 (s)、23 位小数有效位 (f) 和 8 位偏置指数 (e)。
(-1)^s * 1.f * 2^(e-127)
在 16777216 的情况下,s = 0, f = 00000000000000000000000(23 个零),e = 151 = 10010111
即。 1.00000000000000000000000 * 2^24
在内存中,我希望它看起来像这样(符号位、小数有效数、有偏指数):
0 00000000000000000000000 10010111
或以字节为单位:
00000000 00000000 00000000 10010111
但它给了我这个:
00000000 00000000 10000000 01001011
看起来偏置指数中缺少最后一位,并且在第 3 个字节的开头随机出现 1,这是为什么呢?
我能够通过反转每个字节中的位来找到正确的指数:
00000000 00000000 00000001 11010010
取出最后 9 位并再次反转它们:
00000000 00000000 0000000 010010111
现在和我预期的一样,但是这个奇怪的顺序是怎么回事?
这个二进制数是以什么格式存储的?
这是我的代码:
using System;
using System.Linq;
namespace SinglePrecision
{
class Program
{
static void Main(string[] args)
{
Single a = 16777216;
byte[] aBytes = BitConverter.GetBytes(a);
string s = string.Join(" ", aBytes.Select(x => Convert.ToString(x, 2).PadLeft(8, '0')));
//s = 00000000 00000000 10000000 01001011
}
}
}
【问题讨论】:
-
GetBytes 方法返回的数组中字节的顺序取决于计算机体系结构是 little-endian 还是 big-endian。
标签: c# math floating-point binary .net-4.7.2