Write bits in different bytes c c++ -
this question exact duplicate of:
i have declared array of bytes:
uint8_t memory[123];
which have filled with:
memory[0]=0xff; memory[1]=0x00; memory[2]=0xff; memory[3]=0x00; memory[4]=0xff;
and requests user write in bits. example, user provides starting bit (ex:10), amount of bits (ex:9) , bits set. in example provided receive 2 bytes:
setbit[0]=0b11110010; setbit[1]=0b00000001; //padded zeros bits
this used modbus big-endian protocol. have come following code:
for(int j=findbyteinit;j<(findbytefinal);j++){ aux[0]=(unsigned char) (setbit[j]>>(startingbit-(8*findbyteinit))); aux[1]=(unsigned char) (setbit[j+1]<<(startingbit-(8*findbyteinit))); memory[j]=(unsigned char) (aux[0] & memory[j] ); memory[j+1]=(unsigned char) (aux[1] & memory[j+1] ); aux[0]=0x00;//clean aux aux[1]=0x00; }
which not work should close ideal solution. suggestions?
i think should work. i've tested lightly.
int start_bit = 10; int bit_count = 9; uint8_t setbit[2] = { 0b11110010, 0b00000001 }; int setbit_size = (bit_count + (char_bit - 1)) / char_bit; int start_byte = start_bit / char_bit; int shift = start_bit % char_bit; int modified_bytes = bit_count ? (bit_count + shift + (char_bit - 1)) / char_bit : 0; (int = 0; < modified_bytes; ++i) { uint8_t mask = 0xff; if (i == 0) { mask <<= shift; } else if (i == modified_bytes - 1) { mask >>= char_bit - (bit_count + shift) % char_bit; } uint8_t carried = > 0 ? (setbit[i - 1] >> (char_bit - shift)) : 0; uint8_t added = < setbit_size ? static_cast<uint8_t>(setbit[i] << shift) : 0; memory[start_byte + i] = (memory[start_byte + i] & ~mask) | ((carried | added) & mask); }
Comments
Post a Comment