简体   繁体   中英

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

I have a vector of integers vector<int> that has 48 items in it. I want to extract binary data out of this(not sure if this is correct way to call it please edit it if it's wrong) ie a sequence of one or more bits and then convert them to a primitive type like int. I have come up with this solution:

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;
}

but this function is long, difficult to read and is done in C style. could someone please suggest a C++ way of doing this. I'm almost certain that C++ has a good, short and elegant way of doing this. also please edit the question so others with similar problem can benefit from it. Unfortunately My English is not that good to express it in a more general way.

EDIT:

as requested in comments for example I want to extract following information with following positions and length:

int year = extractValue(data, 0, 6);
int month = extractValue(data, 7, 10);
int day = extractValue(data, 11, 15);

a simple solution:

  • convert each byte to hex string ( ostringstream or even sprintf can help), you got 2 digits, range is 0 to F.
  • for each hex digit you can create the bitmap like this:

    0 = 0000, 1 = 0001, 2 = 0010, ..., F = 1111,

  • add bits to the vector according to the bitmap

  • to recover - you take 4 bits and translate it back to digit, then take 2 digits and convert back to byte (say by adding 0x to the hex, isringstream to byte).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM