从8位字节中提取二进制数据并将其转换为基本类型[c++]

extracting binary data out of 8-bit byte and converting it to primitive types [C++]

本文关键字:转换 类型 c++ 字节 8位 提取 二进制 数据      更新时间:2023-10-16

我有一个整数向量vector<int>,其中有48个项目。我想从中提取二进制数据(不确定这是否是正确的方式来调用它,请编辑它,如果它是错误的),即一个或多个位的序列,然后将它们转换为像int这样的基本类型。我想到了这样一个解决方案:

int extractValue(vector<int> v, int startBit, int endBit) {
    int beginByteIndex = (startBit / 8);
    int endByteIndex = (endBit / 8);
    vector<bool> bits;
    bits.clear();
    int startIndex = startBit % 8;
    int endIndex = endBit % 8;
    int value = v[beginByteIndex];
    value = (value << startIndex);
    int temp = 8;
    if (beginByteIndex == endByteIndex) {
        temp = endIndex + 1;
    }
    for (int i = startIndex; i < temp; i++) {
        int temp = 0x80 & value;
        bits.push_back(temp);
        value <<= 1;
    }
    for (int i = beginByteIndex + 1; i < endByteIndex; i++) {
        value = v[i];
        for (int j = 0; j < 8; j++) {
            int temp = 0x80 & value;
            bits.push_back(temp);
            value <<= 1;
        }
    }
    if (endByteIndex > beginByteIndex) {
        value = v[endByteIndex];
        for (int i = 0; i <= endIndex; i++) {
            int temp = 0x80 & value;
            bits.push_back(temp);
            value <<= 1;
        }
    }
    int size = bits.size();
    int p = 1;
    int result = 0;
    for (int i = size - 1; i >= 0; i--) {
        result += (bits[i] * p);
        p *= 2;
    }
    return result;
}

,但是这个函数很长,难以阅读,并且是用C语言完成的。有人可以建议一个c++的方式做到这一点。我几乎可以肯定c++有一种很好的、简短的、优雅的方法来实现这一点。也请编辑问题,这样其他有类似问题的人可以从中受益。遗憾的是,我的英语不太好,无法用更一般的方式表达出来。

编辑:

例如,我想提取以下信息与以下位置和长度:
int year = extractValue(data, 0, 6);
int month = extractValue(data, 7, 10);
int day = extractValue(data, 11, 15);

一个简单的解决方案:

  • 将每个字节转换为十六进制字符串(ostringstreamsprintf甚至可以帮助),您得到2位数字,范围为0到f
  • 对于每个十六进制数字,您可以像这样创建位图:

    0 = 0000;1 = 0001;2 = 0010;…,F = 1111,

  • 根据位图向矢量添加位

  • 恢复-您采取4位并将其转换回数字,然后采取2位并转换回字节(例如通过将0x添加到十六进制,isringstream到字节)。