我有65个不同位长的参数,我需要填写一个八位字符串。参数将连续填入八进制字符串。例如,假设第一个参数是1位长,所以它将在八位字符串的第1个八位字节的第0位位置填充。现在第二个参数是假设9位长。因此,这个参数的前7位将填充在同一个八位字节中,接下来的2位将进入下一个八位字节的第0位和第1位位置。类似地,其他参数将被填充到八进制字符串中。我试着写一个函数,在这个函数中,我把指针传递给当前的八位字节、位位置和源指针,从中复制数据。但我发现逻辑表达有困难。我尝试过很多逻辑(位操作、位移位、旋转等),但都没有得到正确的逻辑。如果有人能给我一个“C”中的逻辑/函数,我将非常感激。也可以使用不同的函数原型。
我写了一个16位的代码如下:

    void set16BitVal(U8** p_buf, U8* bitPos, U16 src)
{
        U16 ctr;
        U16 bitVal;
        U16 srcBitVal;
        U16 tempSrc = src;
        U8 temp = **p_buf;
        printf("\n temp = %d\n", temp);
        for(ctr=0; ctr<16; ctr++)
        {
         bitVal = 1;
         bitVal = bitVal << ctr;
         srcBitVal = src & bitVal;

      temp = temp | srcBitVal;
      **p_buf = temp;

      if(srcBitVal)
        srcBitVal = 1;
      else
        srcBitVal = 0;

      printf("\n bit = %d, p_buf = %x \t p_buf=%d  bitPos=%d ctr=%d srcBitVal = %d\n",\
              tempSrc, *p_buf, **p_buf, *bitPos, ctr, srcBitVal);
      *bitPos = (*bitPos+1)%8; /*wrap around after bitPos:7 */
      if(0 == *bitPos)
      {
        (*p_buf)++; /*jump to next octet*/
        temp = **p_buf;
        printf("\n Value of temp = %d\n", temp);
      }



      //printf("\n ctr=%d srcBitVal = %d", ctr, srcBitVal);
      printf("\n");
    }
}

但问题是,假设我通过src=54647,得到以下输出:
温度=0
位=54647,p_buf=bf84da4b p_buf=1位pos=0 ctr=0 srcBitVal=1
位=54647,p_buf=bf84da4b p_buf=3位pos=1 ctr=1 srcBitVal=1
位=54647,p_buf=bf84da4b p_buf=7位pos=2 ctr=2 srcBitVal=1
位=54647,p_buf=bf84da4b p_buf=7位pos=3 ctr=3 srcBitVal=0
位=54647,p_buf=bf84da4b p_buf=23位pos=4 ctr=4 srcBitVal=1
位=54647,p_buf=bf84da4b p_buf=55位pos=5 ctr=5 srcBitVal=1
位=54647,p_buf=bf84da4b p_buf=119位pos=6 ctr=6 srcBitVal=1
位=54647,p_buf=bf84da4b p_buf=119位pos=7 ctr=7 srcBitVal=0
温度值=0
位=54647,p_buf=bf84da4c p_buf=0位pos=0 ctr=8 srcBitVal=1
位=54647,p_buf=bf84da4c p_buf=0位pos=1 ctr=9 srcBitVal=0
位=54647,p_buf=bf84da4c p_buf=0位pos=2 ctr=10 srcBitVal=1
位=54647,p_buf=bf84da4c p_buf=0位pos=3 ctr=11 srcBitVal=0
位=54647,p_buf=bf84da4c p_buf=0位pos=4 ctr=12 srcBitVal=1
位=54647,p_buf=bf84da4c p_buf=0位pos=5 ctr=13 srcBitVal=0
位=54647,p_buf=bf84da4c p_buf=0位pos=6 ctr=14 srcBitVal=1
位=54647,p_buf=bf84da4c p_buf=0位pos=7 ctr=15 srcBitVal=1
温度值=0
但是预期的输出是:下一个字节应该开始填充src之后第8位的值。
有人能帮我解决吗?

最佳答案

你真幸运。因为我喜欢比特旋转,所以我为您编写了一个比特缓冲区的通用实现。我没有对它进行彻底的测试(例如,并不是所有讨厌的角落案例),但是正如您将看到的,它通过了我添加到下面代码中的简单测试。

#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

struct BitBuffer {
    unsigned length;       // No of bits used in buffer
    unsigned capacity;     // No of bits available in buffer
    uint8_t buffer[];
};

struct BitBuffer * newBitBuffer (
    unsigned capacityInBits
) {
    int capacityInBytes;
    struct BitBuffer * result;

    capacityInBytes = (capacityInBits / 8);
    if (capacityInBits % 8 != 0) {
        capacityInBytes++;
    }

    result = malloc(sizeof(*result) + capacityInBytes);
    if (result) {
        result->length = 0;
        result->capacity = capacityInBits;
    }
    return result;
}

bool addBitsToBuffer (
    struct BitBuffer * bbuffer, const void * bits, unsigned bitCount
) {
    unsigned tmpBuf;
    unsigned tmpBufLen;
    unsigned tmpBufMask;
    uint8_t * nextBufBytePtr;
    const uint8_t * nextBitsBytePtr;

    // Verify input parameters are sane
    if (!bbuffer || !bits) {
        // Evil!
        return false;
    }
    if (bitCount == 0) {
        // No data to add? Nothing to do.
        return true;
    }

    // Verify we have enough space available
    if (bbuffer->length + bitCount > bbuffer->capacity) {
        // Won't fit!
        return false;
    }

    // Get the first byte we start writing bits to
    nextBufBytePtr = bbuffer->buffer + (bbuffer->length / 8);

    // Shortcut:
    // If we happen to be at a byte boundary,
    // we can simply use memcpy and save us a lot of headache.
    if (bbuffer->length % 8 == 0) {
        unsigned byteCount;

        byteCount = bitCount / 8;
        if (bitCount % 8 != 0) {
            byteCount++;
        }
        memcpy(nextBufBytePtr, bits, byteCount);
        bbuffer->length += bitCount;
        return true;
    }

    // Let the bit twiddling begin
    nextBitsBytePtr = bits;
    tmpBuf = *nextBufBytePtr;
    tmpBufLen = bbuffer->length % 8;
    tmpBuf >>= 8 - tmpBufLen;
    tmpBufMask = (~0u) >> ((sizeof(unsigned) * 8) - tmpBufLen);
    // tmpBufMask has the first tmpBufLen bits set to 1.
    // E.g. "tmpBufLen == 3" ==> "tmpBufMask == 0b111 (7)"
    // or "tmpBufLen == 6" ==> "tmpBufMask = 0b111111 (63)", and so on.

    // Beyond this point we will neither access bbuffer->length again, nor
    // can this function fail anymore, so we set the final length already.
    bbuffer->length += bitCount;

    // Process input bits in byte chunks as long as possible
    while (bitCount >= 8) {
        // Add 8 bits to tmpBuf
        tmpBuf = (tmpBuf << 8) | *nextBitsBytePtr;
        // tmpBuf now has "8 + tmpBufLen" bits set

        // Add the highest 8 bits of tmpBuf to our BitBuffer
        *nextBufBytePtr = (uint8_t)(tmpBuf >> tmpBufLen);

        // Cut off the highest 8 bits of tmpBuf
        tmpBuf &= tmpBufMask;
        // tmpBuf now has tmpBufLen bits set again

        // Skip to next input/output byte
        bitCount -= 8;
        nextBufBytePtr++;
        nextBitsBytePtr++;
    }

    // Test if we still have bits left. That will be the case
    // if the input bit count was no integral multiple of 8.
    if (bitCount != 0) {
        // Add bitCount bits to tmpBuf
        tmpBuf = (tmpBuf << bitCount) | (*nextBitsBytePtr >> (8 - bitCount));
        tmpBufLen += bitCount;
    }

    // tmpBufLen is never 0 here, it must have a value in the range [1, 14].
    // We add zero bits to it so that tmpBuf has 16 bits set.
    tmpBuf <<= (16 - tmpBufLen);

    // Now we only need to add one or two more bytes from tmpBuf to our
    // BitBuffer, depending on its length prior to adding the zero bits.
    *nextBufBytePtr = (uint8_t)(tmpBuf >> 8);
    if (tmpBufLen > 8) {
        *(++nextBufBytePtr) = (uint8_t)(tmpBuf & 0xFF);
    }
    return true;
}



int main ()
{
    bool res;
    uint8_t testData[4];
    struct BitBuffer * buf;

    buf = newBitBuffer(1024); // Can hold up to 1024 bits
    assert(buf);

    // Let's add some test data.

    // Add 1 bit "1" => Buffer "1"
    testData[0] = 0xFF;
    res = addBitsToBuffer(buf, testData, 1);
    assert(res);

    // Add 6 bits "0101 01" => Buffer "1010 101"
    testData[0] = 0x54;
    res = addBitsToBuffer(buf, testData, 6);
    assert(res);

    // Add 4 Bits "1100" => Buffer "1010 1011 100"
    testData[0] = 0xC0;
    res = addBitsToBuffer(buf, testData, 4);
    assert(res);

    // Add 16 Bits "0111 1010 0011 0110"
    // ==> Buffer "1010 1011 1000 1111 0100 0110 110
    testData[0] = 0x7A;
    testData[1] = 0x36;
    res = addBitsToBuffer(buf, testData, 16);
    assert(res);

    // Add 5 Bits "0001 1"
    // ==> Buffer "1010 1011 1000 1111 0100 0110 1100 0011"
    testData[0] = 0x18;
    res = addBitsToBuffer(buf, testData, 5);
    assert(res);

    // Buffer should now have exactly a length of 32 bits
    assert(buf->length == 32);

    // And it should have the value 0xAB8F46C3
    testData[0] = 0xAB;
    testData[1] = 0x8F;
    testData[2] = 0x46;
    testData[3] = 0xC3;
    assert(memcmp(buf->buffer, testData, 4) == 0);

    free(buf);
    return 0;
}

代码没有优化以达到最大性能,但我想它应该有一个不错的性能。任何额外的性能调整都会显著增加代码的大小,我希望代码保持相当简单。有些人可能会争辩说,使用>> 3而不是/ 8& 0x7而不是% 8会带来更好的性能,但是如果您使用一个好的C编译器,那么这正是编译器在内部所做的,如果您启用了优化,因此我宁愿让代码更可读。
附加说明
当您将指针传递给多字节数据类型时,请注意字节顺序!例如,以下代码
 uint16_t x16 = ...;
 addBitsToBuffer(buf, &x16, ...);
 uint32_t x32 = ...;
 addBitsToBuffer(buf, &x32, ...);

在大端机(PPC CPU)上运行良好,但在小端机(如x86cpu)上可能不会产生预期的结果。在一个小型的endian机器上,你必须先交换字节顺序。您可以将htonshtonl用于此目的:
 uint16_t x16 = ...;
 uint16_t x16be = htons(x16);
 addBitsToBuffer(buf, &x16be, ...);
 uint32_t x32 = ...;
 uint32_t x32be = htonl(x32);
 addBitsToBuffer(buf, &x32be, ...);

在大端机上,htonX函数/宏通常什么也不做,因为值已经在“网络字节顺序”(big endian)中,而在小端机上,它们将交换字节顺序。
传递一个uint8_t指针总是在两台机器上工作,它只是一个字节,因此没有字节顺序。

关于c - 填充八位字节字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14231464/

10-12 06:05