Mono DataConvert 可以用来读取 3 字节整数吗?

发布于 2025-01-06 19:24:57 字数 836 浏览 5 评论 0原文

我正在尝试读取特定的二进制文件,但它包含 3 字节大端整数。我最近遇到了 Mono DataConvert,它应该可以满足我想要的大部分功能,除了这些3 字节整数。我不知道如何阅读它们。请注意,我不需要将它们保留为 3 字节整数,将它们读入常规 Int32 将是理想的选择。我正在读取大量数据,因此我正在寻找有效的东西。有什么建议吗?


理想代码示例:

public Region(string regionFile)
{
    var conv = DataConverter.BigEndian;
    var chunks = new Chunk[Chunk.MaxLocations];
    using (var fs = File.OpenRead(regionFile))
    {
        var buffer = new byte[4096];
        fs.Read(buffer, 0, buffer.Length);

        // Read chunk locations
        for (int i = 0; i < Chunk.MaxLocations; ++i)
        {
            chunks[i] = new Chunk(conv.ToInt24(buffer, i * 4), buffer[i * 4 + 3]);
        }
    }
}

我想做类似的事情,但 conv.ToInt24 不存在。我想我可以通过位移来编写自己的......

I'm trying to read a particular binary file, but it contains 3-byte big-endian integers. I came across Mono DataConvert recently, which should be nice for most of what I want, except for these 3-byte integers. I'm not sure how to read them. Note that I don't need to keep them as 3-byte integers, reading them into a regular Int32 would be ideal. I'm reading in a good chunk of data, so I'm looking for something efficient. Any suggestions?


Sample ideal code:

public Region(string regionFile)
{
    var conv = DataConverter.BigEndian;
    var chunks = new Chunk[Chunk.MaxLocations];
    using (var fs = File.OpenRead(regionFile))
    {
        var buffer = new byte[4096];
        fs.Read(buffer, 0, buffer.Length);

        // Read chunk locations
        for (int i = 0; i < Chunk.MaxLocations; ++i)
        {
            chunks[i] = new Chunk(conv.ToInt24(buffer, i * 4), buffer[i * 4 + 3]);
        }
    }
}

I want to do something like that, except conv.ToInt24 doesn't exist. I guess I could write my own by bit-shifting...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

后来的我们 2025-01-13 19:24:57

我复制了 Mono 的 GetInt32 并稍作修改:

public override int GetInt24(byte[] data, int index)
{
    if (data == null)
        throw new ArgumentNullException("data");
    if (data.Length - index < 3)
        throw new ArgumentException("index");
    if (index < 0)
        throw new ArgumentException("index");

    int ret = 0;
    byte* b = (byte*)&ret;

    for (int i = 0; i < 3; i++)
        b[2 - i] = data[index + i];

    return ret;
}

似乎可以工作。

I copied Mono's GetInt32 and modified it slightly:

public override int GetInt24(byte[] data, int index)
{
    if (data == null)
        throw new ArgumentNullException("data");
    if (data.Length - index < 3)
        throw new ArgumentException("index");
    if (index < 0)
        throw new ArgumentException("index");

    int ret = 0;
    byte* b = (byte*)&ret;

    for (int i = 0; i < 3; i++)
        b[2 - i] = data[index + i];

    return ret;
}

Seems to work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文