解码十六进制格式

时间:2018-04-26 07:33:34

标签: matrix hex transform decoding

我有十六进制的字符串: "0000803F00000000000000B4B410D1A90000803FB41051B500000034B41051350000803F000000000000000000C05B400000000000C06B400000000000D07440"

我知道它包含什么:

  

(1,0,-1.192093e-007),

     

( - 9.284362e-014,1,-7.788287e-007),

     

(1.192093e-007,7.788287e-007,1),

     

(111,222,333)。

是的,这是一个转换矩阵!

解码前72个字符(每个数字8个字符)是微不足道的,你只需要拆分8并使用IEEE浮点格式即。 0x0000803F = 1.0f

所以我们仍然有"000000000000000000C05B400000000000C06B400000000000D07440"包含第四个向量,但我从未见过这种数字编码。

虽然这个吗?

1 个答案:

答案 0 :(得分:1)

看起来这些是8字节的IEEE浮点数,从字节40开始。所以布局是:

  • 字节0-11:第一个向量,3个单精度数
  • 字节12-23:第二个向量,3个单精度数
  • 字节25-35:第三个向量,3个单精度数
  • 字节36-39:未使用? (填充?)
  • 字节40-63:第四个向量,3个双精度数字

下面的代码显示了在C#中解析它的示例。代码的输出是:

(1, 0, -1.192093E-07)
(-9.284362E-14, 1, -7.788287E-07)
(1.192093E-07, 7.788287E-07, 1)
(111, 222, 333)

示例代码:

using System;

class Program
{
    static void Main(string[] args)
    {
        string text = "0000803F00000000000000B4B410D1A90000803FB41051B500000034B41051350000803F000000000000000000C05B400000000000C06B400000000000D07440";
        byte[] bytes = ParseHex(text);

        for (int i = 0; i < 3; i++)
        {
            float x = BitConverter.ToSingle(bytes, i * 12);
            float y = BitConverter.ToSingle(bytes, i * 12 + 4);
            float z = BitConverter.ToSingle(bytes, i * 12 + 8);
            Console.WriteLine($"({x}, {y}, {z})");
        }

        // Final vector
        {
            double x = BitConverter.ToDouble(bytes, 40);
            double y = BitConverter.ToDouble(bytes, 48);
            double z = BitConverter.ToDouble(bytes, 56);
            Console.WriteLine($"({x}, {y}, {z})");
        }
    }

    // From https://stackoverflow.com/a/854026/9574109
    public static byte[] ParseHex(string hex)
    {
        int offset = hex.StartsWith("0x") ? 2 : 0;
        if ((hex.Length % 2) != 0)
        {
            throw new ArgumentException("Invalid length: " + hex.Length);
        }
        byte[] ret = new byte[(hex.Length-offset)/2];

        for (int i=0; i < ret.Length; i++)
        {
            ret[i] = (byte) ((ParseNybble(hex[offset]) << 4) 
                             | ParseNybble(hex[offset+1]));
            offset += 2;
        }
        return ret;
    }        

    static int ParseNybble(char c)
    {
        if (c >= '0' && c <= '9')
        {
            return c-'0';
        }
        if (c >= 'A' && c <= 'F')
        {
            return c-'A'+10;
        }
        if (c >= 'a' && c <= 'f')
        {
            return c-'a'+10;
        }
        throw new ArgumentException("Invalid hex digit: " + c);
    }
}