Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- int main1() {
- int a = 2'000'000'000;
- int b = a << 1;
- std::cout << b << std::endl;
- while (b) {
- b >>= 1;
- std::cout << b << std::endl;
- }
- return 0;
- }
- int main2() {
- unsigned int n; std::cin >> n;
- int count = -1;
- while (n) {
- count++;
- n >>= 1;
- }
- std::cout << count << std::endl;
- return 0;
- }
- typedef char byte;
- struct IInputStream {
- // Возвращает false, если поток закончился
- virtual bool Read(byte& value) = 0;
- };
- struct IOutputStream {
- virtual void Write(byte value) = 0;
- };
- class InputString : public IInputStream {
- public:
- explicit InputString(std::string s_) : s(std::move(s_)) {}
- bool Read(byte& value) override {
- if (current >= s.length()) return false;
- value = s[current++];
- return true;
- }
- private:
- std::string s;
- int current = 0;
- };
- class OutputCout : public IOutputStream {
- public:
- void Write(byte value) override { std::cout << value; }
- };
- class OutputCout2 : public IOutputStream {
- public:
- void Write(byte value) override {
- for (int i = 7; i >= 0; --i) std::cout << ((value >> i) & 1);
- std::cout << " ";
- }
- };
- class OutputAdapter {
- public:
- explicit OutputAdapter(IOutputStream& out_) : out(out_) {}
- void WriteBit(bool bit);
- void WriteByte(byte b);
- void Finish();
- private:
- IOutputStream& out;
- byte buffer; // 8 бит буфера, накапливается перед сбросом в out.
- int cursor = 0; // Число заполненных битов в buffer. Используются cursor младших битов в buffer.
- };
- // 10110001|01010aaa|aaaaa
- //
- void OutputAdapter::WriteBit(bool bit) {
- // 000|01101 -> 00|011010 -> 00|011011
- buffer = (buffer << 1) + bit;
- ++cursor;
- if (cursor == 8) {
- out.Write(buffer);
- cursor = 0;
- }
- }
- void OutputAdapter::WriteByte(byte b) {
- // 00000|010 + AAAAAaaa -> 010AAAAA + 00000|aaa
- int shift = 8 - cursor;
- byte value = (buffer << shift) | (b >> cursor);
- out.Write(value);
- buffer = ((int)(b << shift) & 0x000000FF) >> shift; // buffer = b & 0b00000111;
- }
- void OutputAdapter::Finish() {
- if (cursor != 0) {
- int shift = 8 - cursor;
- // 10000000 >> 7 -> 11111111
- buffer = ((int)(buffer << shift) & 0x000000FF) >> shift;
- out.Write(buffer);
- }
- out.Write((byte)(cursor));
- }
- void Encode(IInputStream& original, IOutputStream& compressed) {
- OutputAdapter outAdapter(compressed);
- byte value;
- while (original.Read(value)) {
- outAdapter.WriteByte(value);
- }
- }
- int main3() {
- std::string s;
- std::cin >> s;
- InputString source(s);
- OutputCout target;
- Encode(source, target);
- return 0;
- }
- int main() {
- OutputCout2 out;
- OutputAdapter adapter(out);
- adapter.WriteByte('a');
- adapter.WriteBit(true);
- adapter.WriteByte('a');
- adapter.Finish();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement