开发者

Decoding Decimal64 data

I'm looking for a simple way to decode data stored in the Decimal64 format (described here: http://en.wikipedia.org/wiki/Dec开发者_如何学Pythonimal64_floating-point_format) using C#.

Any thoughts?


Looked everywhere for it, finally we implemented it ourselves.

Update Some of you has asked us for the code - here is our code for it, We call it Float Decimal, I think it matches what Decimal 64 does - but no guarantees - please check for yourself.

Also note - that the value of _size should be 8.

 if (bytes[0] == 0) return 0;
        var s = "";
        for (var i = 1; i < bytes.Length; i++)
            s += bytes[i].ToString("X").PadLeft(2, '0');
        return decimal.Parse("." + s.TrimEnd('0')) * (decimal)Math.Pow(10 , ((bytes[0] & ~128) - 64)) * ((bytes[0] & 128) > 0 ? -1 : 1);

To save:

 if (value != 0)
        {
            var negative = value < 0;
            var s = value.ToDecimal().ToString(CultureInfo.InvariantCulture).TrimStart('-', '0');
            var i = s.IndexOf('.');
            if (i >= 0)
            {
                s = s.Remove(i, 1);
                if (i == 0)
                {
                    i = s.Length;
                    s = s.TrimStart('0');
                    i = s.Length-i;
                }
            }
            else i = s.Length;
            bytes[0] = (byte)(64 + i + (negative ? 128 : 0));
            s = s.PadRight((_size - 1) * 2, '0');
            for (var j = 1; j < _size && (j - 1) * 2 < s.Length; j++)
                bytes[j] = byte.Parse(s.Substring((j - 1) * 2, 2), System.Globalization.NumberStyles.HexNumber);
        }


Read a bit too fast there.

I think you'd want to have a look at the BitConverter.ToSingle method in C# but reverse the order of the bytes to get a correct result. :)

B.R Jaggernauten

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜