Advertisement
amigojapan

boost dynamic bitset bytes converter 2 way

Apr 8th, 2015
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include <ostream>
  2. #include <iostream>
  3. //#include<stdio.h>
  4.  
  5. #include <cstdlib>
  6. #include <iterator>
  7. #include <vector>
  8. #include <boost/dynamic_bitset.hpp>
  9.  
  10. // Make the block size one byte
  11. typedef boost::dynamic_bitset<unsigned char> Bitset;
  12. typedef std::vector<unsigned char> bytesArray;
  13. bytesArray dynamic_bitset_to_bytes(Bitset bitset){
  14.     bytesArray bytes;
  15.     boost::to_block_range(bitset, std::back_inserter(bytes));  
  16.     return bytes;
  17. }
  18.  
  19. Bitset convert_bytes_to_dynamic_bitset(int bitset_size, bytesArray bytes){
  20.     //revert values from bytes to dynamic bitset
  21.     Bitset bitset2(bitset_size);
  22.     int bitcount=0;
  23.     for(int byteCount=0; byteCount<bytes.size(); ++byteCount) {
  24.         int mask=0x80;
  25.         for(int individualBit=8; individualBit>0;--individualBit) {
  26.             bitset2[(byteCount*8) + individualBit-1]=bytes[byteCount] & mask ? 1 : 0;
  27.             mask >>= 1;
  28.         }
  29.        
  30.     }
  31.     return bitset2;
  32. }
  33.  
  34.  
  35. int main()
  36. {
  37.  
  38.     Bitset bitset(40); // 40 bits
  39.  
  40.     // Assign random bits
  41.     for (int i=0; i<40; ++i)
  42.     {
  43.         bitset[i] = std::rand() % 2;
  44.     }
  45.  
  46.     // Copy bytes to buffer
  47.     bytesArray bytes;
  48.     bytes = dynamic_bitset_to_bytes(bitset);
  49.    
  50.     Bitset bitset2(40);
  51.    
  52.     bitset2 = convert_bytes_to_dynamic_bitset(40, bytes);
  53.    
  54.    
  55.     std::cout << "bitset1: " << bitset << std::endl;
  56.     std::cout << "bitset2: " << bitset2 << std::endl;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement