开发者

Delphi Extended to C#

开发者 https://www.devze.com 2023-01-01 10:00 出处:网络
how to convert a floating point 10 byte Hex string (Extended datatype in Delphi) to a C# datatype? For example:

how to convert a floating point 10 byte Hex string (Extended datatype in Delphi) to a C# datatype?

For example: 00 00 00 00 00 00 00 80 ff 3f开发者_如何学编程 is at Delphi 1


Was involved in same issue, sharing my solution somebody can find useful:

        var extendedSize = 10;
        var buf = new byte[extendedSize];

        // Populate buffer with something like: { 0x00, 0x68, 0x66, 0x66, 0x66, 0x66, 0x66, 0xA2, 0x02, 0x40 } = 10.15
        // Read(buf, extendedSize);

        var sign = (buf[extendedSize - 1] & 0x80) == 0x80 ? -1 : 1;
        buf[extendedSize - 1] = (byte)(buf[extendedSize - 1] & 0x7F);
        var exp = BitConverter.ToUInt16(buf, extendedSize - 2);
        var integral = (buf[extendedSize - 3] & 0x80) == 0x80 ? 1 : 0;           

        // Calculate mantissa
        var mantissa = 0.0;
        var value = 1.0;
        var fractal = BitConverter.ToUInt64(buf, 0);

        while (fractal != 0)
        {
            value = value / 2;
            if ((fractal & 0x4000000000000000) == 0x4000000000000000) // Latest bit is sign, just skip it
            {
                mantissa += value;
            }
            fractal <<= 1;
        }

        return sign * (Math.Pow(2, exp - 16383)) * (integral + mantissa);    

Code needs to be improved with NaN and Inf checks and probably "double" needs to be replaced by "decimal".


Ok, here is my solution:

Every string contains a factor byte at the second position. In my example the factor is ff.

Now I have to convert the string via Floating-Point Conversion to decimal and multiply with the factor byte to get the result.

Example: 3f ff 80 00 00 (32bit) -> remove the factor byte (ff) -> 3f 80 00 00 -> convert to decimal -> result: 1 -> multiply with factor -> 1 * 1 -> result: 1

I hope this was helpfully

0

精彩评论

暂无评论...
验证码 换一张
取 消