45 lines
978 B
C++
45 lines
978 B
C++
|
#include <bit>
|
||
|
#include <climits>
|
||
|
#include <cmath>
|
||
|
#include <cstdio>
|
||
|
|
||
|
class BinaryEncoder {
|
||
|
private:
|
||
|
unsigned char *const buffer;
|
||
|
std::size_t index;
|
||
|
|
||
|
public:
|
||
|
BinaryEncoder(unsigned char *b) noexcept : buffer(b) {}
|
||
|
|
||
|
void write(unsigned char val, unsigned char width = 0)
|
||
|
{
|
||
|
if (width == 0)
|
||
|
width = std::bit_width(val);
|
||
|
|
||
|
const unsigned char bitindex = index % CHAR_BIT;
|
||
|
const std::size_t byteindex = index / CHAR_BIT;
|
||
|
|
||
|
buffer[byteindex] &= compl(UCHAR_MAX << bitindex);
|
||
|
buffer[byteindex] |= val << bitindex;
|
||
|
|
||
|
const unsigned char bitsWritten = CHAR_BIT - bitindex;
|
||
|
|
||
|
if (width <= bitsWritten) {
|
||
|
index += width;
|
||
|
} else {
|
||
|
index += bitsWritten;
|
||
|
this->write(val >> bitsWritten);
|
||
|
}
|
||
|
}
|
||
|
};
|
||
|
|
||
|
|
||
|
int main() {
|
||
|
unsigned char buf[1];
|
||
|
BinaryEncoder be(buf);
|
||
|
|
||
|
be.write(0b111u);
|
||
|
be.write(0b100u);
|
||
|
|
||
|
if (buf[0] == 39) std::puts("miku");
|
||
|
}
|