C# 双精度数转实数
我正在尝试将双精度数转换为帕斯卡实数,但是当我将 0.23 转换为实数时,我得到了 0.23999999 实数,如何将所有 9999 截断为 0000。
public static byte[] Double2Real48(double d)
{
byte[] r48 = new byte[6];
byte[] da = BitConverter.GetBytes(d);
for (int i = 0; i < r48.Length; i++)
r48[i] = 0;
//Copy the negative flag
r48[5] |= (byte)(da[7] & 0x80);
//Get the expoent
byte b1 = (byte)(da[7] & 0x7f);
ushort n = (ushort)(b1 << 4);
byte b2 = (byte)(da[6] & 0xf0);
b2 >>= 4;
n |= b2;
if (n == 0)
return r48;
byte ex = (byte)(n - 1023);
r48[0] = (byte)(ex + 129);
//Copy the Mantissa
r48[5] |= (byte)((da[6] & 0x0f) << 3);//Get the last four bits
r48[5] |= (byte)((da[5] & 0xe0) >> 5);//Get the first three bits
r48[4] = (byte)((da[5] & 0x1f) << 3);//Get the last 5 bits
r48[4] |= (byte)((da[4] & 0xe0) >> 5);//Get the first three bits
r48[3] = (byte)((da[4] & 0x1f) << 3);//Get the last 5 bits
r48[3] |= (byte)((da[3] & 0xe0) >> 5);//Get the first three bits
r48[2] = (byte)((da[3] & 0x1f) << 3);//Get the last 5 bits
r48[2] |= (byte)((da[2] & 0xe0) >> 5);//Get the first three bits
r48[1] = (byte)((da[2] & 0x1f) << 3);//Get the last 5 bits
r48[1] |= (byte)((da[1] & 0xe0) >> 5);//Get the first three bits
return r48;
}
i am trying to convert double to pascal real but when i convert 0.23 to real i got 0.23999999 real how can i truncate all 9999 to 0000.
public static byte[] Double2Real48(double d)
{
byte[] r48 = new byte[6];
byte[] da = BitConverter.GetBytes(d);
for (int i = 0; i < r48.Length; i++)
r48[i] = 0;
//Copy the negative flag
r48[5] |= (byte)(da[7] & 0x80);
//Get the expoent
byte b1 = (byte)(da[7] & 0x7f);
ushort n = (ushort)(b1 << 4);
byte b2 = (byte)(da[6] & 0xf0);
b2 >>= 4;
n |= b2;
if (n == 0)
return r48;
byte ex = (byte)(n - 1023);
r48[0] = (byte)(ex + 129);
//Copy the Mantissa
r48[5] |= (byte)((da[6] & 0x0f) << 3);//Get the last four bits
r48[5] |= (byte)((da[5] & 0xe0) >> 5);//Get the first three bits
r48[4] = (byte)((da[5] & 0x1f) << 3);//Get the last 5 bits
r48[4] |= (byte)((da[4] & 0xe0) >> 5);//Get the first three bits
r48[3] = (byte)((da[4] & 0x1f) << 3);//Get the last 5 bits
r48[3] |= (byte)((da[3] & 0xe0) >> 5);//Get the first three bits
r48[2] = (byte)((da[3] & 0x1f) << 3);//Get the last 5 bits
r48[2] |= (byte)((da[2] & 0xe0) >> 5);//Get the first three bits
r48[1] = (byte)((da[2] & 0x1f) << 3);//Get the last 5 bits
r48[1] |= (byte)((da[1] & 0xe0) >> 5);//Get the first three bits
return r48;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是我的转换例程。请注意,我没有在此处放置任何特殊内容来处理 IEEE 无穷大或 NaN 值。
往返转换会造成一些精度损失,但结果基本上是正确的。 [Real48ToDouble(DoubleToReal48(0.23)) 返回 0.229999999999563]
Here are my conversion routines. Note that I haven't put anything special here for treating IEEE infinities or NaN values.
There is some loss of precision with roundtrip conversions, but the results are basically correct. [Real48ToDouble(DoubleToReal48(0.23)) returns 0.229999999999563]