gpt4 book ai didi

c# - 将 C# double 转换为 Delphi Real48

转载 作者:太空狗 更新时间:2023-10-30 00:46:42 25 4
gpt4 key购买 nike

我发现了以下问题 Convert Delphi Real48 to C# double但我想走另一条路,从 C# 到 Delphi。

有谁知道如何做到这一点?我尝试过对代码进行逆向工程,但运气不佳。

更新:

我正在寻找 C# 代码,该代码将采用 double 并将其转换为 Real48(大小为 6 的 byte[])。

谢谢

最佳答案

我在寻找相同代码时遇到了这个线程。这是我最后写的:

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;

}

Real48 与 IEEE 754 的相似之处在于尾数相同。移位对于使尾数位于正确的位置是必要的。

Real48 指数的偏差为 129, double 指数的偏差为 1023。

负标志存储在最后一个字节的第一位。

注意事项:我不认为这段代码可以在大端机器上运行。它不检查 NAN 或 INF。

这是将 real48 转换为 double 的代码。它是从 Free Pascal 编译器移植而来的:

static double real2double(byte [] r)
{
byte [] res = new byte[8];
int exponent;

//Return zero if the exponent is zero
if (r[0] == 0)
return (double)0;

//Copy Mantissa
res[0] = 0;
res[1] = (byte)(r[1] << 5);
res[2] = (byte)((r[1] >> 3) | (r[2] << 5));
res[3] = (byte)((r[2] >> 3) | (r[3] << 5));
res[4] = (byte)((r[3] >> 3) | (r[4] << 5));
res[5] = (byte)((r[4] >> 3) | ((r[5] & 0x7f) << 5));
res[6] = (byte)((r[5] & 0x7f) >> 3);

//Copy exponent
//correct exponent
exponent = (r[0] + (1023-129));
res[6] = (byte)(res[6] | ((exponent & 0xf) << 4));
res[7] = (byte)(exponent >> 4);

//Set Sign
res[7] = (byte)(res[7] | (r[5] & 0x80));
return BitConverter.ToDouble(res, 0);
}

关于c# - 将 C# double 转换为 Delphi Real48,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2539300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com