fork download
  1. #include <iostream>
  2. #include <cmath>
  3. #include <vector>
  4.  
  5. using namespace std;
  6. using Blob = vector<uint8_t>;
  7.  
  8. // http://stackoverflow.com/questions/29547628/convert-uint8-t-hex-value-to-binary
  9. void toBinary(uint8_t a) {
  10. int tmp = 0;
  11. for(uint8_t i=0x80;i!=0;i>>=1) {
  12. if ( tmp++ % 4 == 0 )
  13. cout << " ";
  14.  
  15. cout << ((a&i)?'1':'0');
  16. }
  17. }
  18.  
  19. void toBinary(Blob p) {
  20. for (size_t i = 0; i < p.size(); i++ )
  21. toBinary(p[i]);
  22. }
  23.  
  24. // Unexpect behavior if a prefix without padding is given.
  25. // No way to check if there is a prefix or if there is not
  26. size_t realPrefix(Blob p) {
  27. for ( size_t i = p.size() - 1; i >= 0; i-- ) {
  28. uint8_t j = 0x01;
  29. for ( size_t pos = 0; pos < 8; pos++, j <<= 1 )
  30. if ( (p[i] & j) != 0x00 )
  31. return pos + ( p.size() - 1 - i) * 8;
  32. }
  33.  
  34. // Should never append
  35. return p.size() * 8;
  36. }
  37.  
  38. int main() {
  39.  
  40. Blob p; // Test Blob
  41. p.push_back(0xBA); // 1011 1010
  42. p.push_back(0x80); // 1000 0000 -> Padding
  43. Blob out(2 * p.size()); // ceil(p.size_ * 2. / 8.);
  44.  
  45. cout << "Prefix with unknown value :" ;
  46. toBinary(p);
  47.  
  48. for ( size_t i = 0; i < p.size(); i++ ) {
  49. for ( int b = 0, shift = 0; b < 8; b++, shift += 2) {
  50. if ( shift >= 8 )
  51. shift = 0;
  52.  
  53. /* 1 -> 11 [0xC0], 0 -> 10 [0x80], shift in right place */
  54. uint8_t mout = (( p[i] & (0x80 >> b ) ) ? 0xC0 : 0x80) >> shift;
  55. out[i * 2 + (b >= 4)] |= mout;
  56. }
  57. }
  58.  
  59. cout << endl << "Output : " ;
  60. toBinary(out);
  61. cout << endl;
  62.  
  63. exit(0);
  64. }
  65.  
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
Prefix with unknown value : 1011 1010 1000 0000
Output :  1110 1111 1110 1110 1110 1010 1010 1010