簡體   English   中英

讀取二進制的 UInt 類型

[英]Read UInt types in binary

我正在實現一個MidiReader ,它需要我讀取天氣 MSB First 或 LSB First UInts(8、16、32 或 64)。 我對二進制和類型知之甚少,所以我目前正在從 C# 復制其他人的代碼。

class ByteArrayReader
{
public:
    unsigned char* ByteArray;
    unsigned int Size;
    unsigned int Index = 0;

    ByteArrayReader(unsigned char* byteArray)
    {
        if (byteArray == NULL)
        {
            throw byteArray;
        }
        ByteArray = byteArray;
        Size = (unsigned int)sizeof(byteArray);
        Index = 0;
    }

    char inline Read()
    {
        return ByteArray[Index++];
    }

    void inline Forward(unsigned int length = 1)
    {
        Index += length;
    }

    void inline Backward(unsigned int length = 1)
    {
        if (length > Index)
        {
            throw length;
        }

        Index -= length;
    }

    bool operator==(ByteArrayReader) = delete;
};

這些是我復制的:


    uint16_t inline ReadUInt16()
    {
        return (uint16_t)((Read() << 8) | Read());
    }

    uint32_t inline ReadUInt32()
    {
        return (uint32_t)((((((Read() << 8) | Read()) << 8) | Read()) << 8) | Read());
    }


但據說其中一個讀取 MSB First UInt。 所以我想問一下如何優雅地從二進制文件中讀取 UInt 類型,同時了解 uint 是如何以字節表示的。

那個部分

(uint32_t)((((((Read() << 8) | Read()) << 8) | Read()) << 8) | Read());

是未定義的行為,因為每次調用Read方法都會增加一個名為Index的計數器,並且編譯器沒有嚴格的計算順序。

如果按這樣的順序計算它們會更好:

auto chunk1 = Read(); // Index=x
auto chunk2 = Read(); // Index=x+1
auto chunk3 = Read(); // Index=x+2
...
auto result = chunk1 << 8 | chunk2<<8 ...

確保增量按順序發生。

小端和大端系統之間的字節順序不同。 這里要求: 在 C++ 程序中以編程方式檢測字節順序

嘗試這個:

uint32_t inline ReadUInt32MSBfirst()
{
    auto b1 = Read();
    auto b2 = Read();
    auto b3 = Read();
    auto b4 = Read();
    return (uint32_t)((b1 << 24) | (b2 << 16) | (b3 << 8) | b4);
}

uint32_t inline ReadUInt32LSBfirst()
{
    auto b1 = Read();
    auto b2 = Read();
    auto b3 = Read();
    auto b4 = Read();
    return (uint32_t)(b1 | (b2 << 8) | (b3 << 16) | (b4 << 24));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM