fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <cmath>
  4.  
  5. using namespace std;
  6. using Blob = vector<uint8_t>;
  7.  
  8. Blob toPrefix(Blob p) {
  9. Blob out(ceil(p.size() / 2.)); // Output is on 1 bit instead of 2 for each data
  10.  
  11. for ( int i = 0; i < p.size(); i++ ) {
  12. if ( (p[i] | 0x55) != 0xFF )
  13. throw std::domain_error("Can not convert to prefix with undefine bits");
  14.  
  15. uint8_t mask = 0x40; // Mqsk for extracting bit a pos x
  16. int shift = ( i % 2 ) ? 3 : 1; // For first uin8_t need to move shift bit to left
  17. // and to right for second uint8_t
  18. // First : 0101 0000 - Second : 1111 0111
  19. // First : Bit pos 1 move to pos 0 - Second : Bit pos 1 move to pos 4
  20.  
  21. for ( int b = 1; b < 8; b += 2, mask >>= 2) { // for each bit of the uint8_t ( jump 1 of 2) and shift j mask
  22. out[i / 2] ^= (
  23. ( i % 2 ) ?
  24. ( p[i] & mask ) >> shift // Get bit pos l, move it to position by shifting of k
  25. : ( p[i] & mask ) << shift
  26. );
  27.  
  28. ( i % 2 ) ? --shift : ++shift; // Next shift to do
  29. }
  30. }
  31.  
  32. return out;
  33. }
  34.  
  35. // http://stackoverflow.com/questions/29547628/convert-uint8-t-hex-value-to-binary
  36. void toBinary(uint8_t a) {
  37. int tmp = 0;
  38. for(uint8_t i=0x80;i!=0;i>>=1) {
  39. if ( tmp++ % 4 == 0 )
  40. cout << " ";
  41.  
  42. cout << ((a&i)?'1':'0');
  43. }
  44. }
  45.  
  46. void toBinary(Blob p) {
  47. for (int i = 0; i < p.size(); i++ )
  48. toBinary(p[i]);
  49. }
  50.  
  51. int main() {
  52.  
  53. Blob p; // Test Blob
  54. p.push_back(0xBA); // 1011 1010
  55.  
  56. Blob out(2 * p.size()); // ceil(p.size_ * 2. / 8.);
  57.  
  58. cout << "Prefix with unknown value :" ;
  59. toBinary(p);
  60. for ( int i = 0; i < p.size(); i++ ) {
  61. for ( int b = 0; b < 8; b++) {
  62. ;
  63. }
  64. }
  65. cout << endl << "Output : ";
  66. toBinary(toPrefix(p));
  67. cout << endl;
  68.  
  69. exit(0);
  70. }
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
Prefix with unknown value : 1011 1010
Output :  0100 0000