fork download
  1. #include <iostream>
  2. #include <bitset>
  3.  
  4. using namespace std;
  5.  
  6. template<std::size_t num_bits>
  7. void writeBits(ostream& os, const std::bitset<num_bits>& thebits)
  8. {
  9. for(std::size_t bit_pos = 0; bit_pos < num_bits;)
  10. {
  11. unsigned char currentByte = 0;
  12. for(int currentBit = 0; currentBit < sizeof(unsigned char) && bit_pos < num_bits; ++currentBit, ++bit_pos)
  13. {
  14. currentByte |= thebits[bit_pos] ? (0x80 >> currentBit) : 0;
  15. }
  16. os << currentByte;
  17. }
  18. }
  19.  
  20. int main() {
  21. std::bitset<4> nibble(std::string("1100"));
  22. std::bitset<8> byte(std::string("11001010"));
  23. std::bitset<23> number_of_bits(std::string("10101010101010101010101"));
  24.  
  25. writeBits(std::cout,nibble);
  26. writeBits(std::cout,byte);
  27. writeBits(std::cout,number_of_bits);
  28.  
  29. return 0;
  30. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
������������������