Extract and combine bits from different bytes c c++

前端 未结 1 1360
滥情空心
滥情空心 2021-01-24 10:35

I have declared an array of bytes:

uint8_t memory[123];

which i have filled with:

memory[0]=0xFF;
memory[1]=0x00;
memory[2]=0x         


        
相关标签:
1条回答
  • 2021-01-24 11:28

    I think this should do it.

    int start_bit = 10, end_bit = 35; // input
    
    int start_byte = start_bit / CHAR_BIT;
    int shift = start_bit % CHAR_BIT;
    int response_size = (end_bit - start_bit + (CHAR_BIT - 1)) / CHAR_BIT;
    int zero_padding = response_size * CHAR_BIT - (end_bit - start_bit + 1);
    
    for (int i = 0; i < response_size; ++i) {
      response[i] =
          static_cast<uint8_t>((memory[start_byte + i] >> shift) |
                               (memory[start_byte + i + 1] << (CHAR_BIT - shift)));
    }
    response[response_size - 1] &= static_cast<uint8_t>(~0) >> zero_padding;
    

    If the input is a starting bit and a number of bits instead of a starting bit and an (inclusive) end bit, then you can use exactly the same code, but compute the above end_bit using:

    int start_bit = 10, count = 9;  // input
    int end_bit = start_bit + count - 1;
    
    0 讨论(0)
提交回复
热议问题