fork(3) download
  1. #include <iostream>
  2. #include <string>
  3. #include <bitset>
  4. #include <sstream>
  5. #include <algorithm>
  6.  
  7. std::string binary_to_hex( const std::string& bits )
  8. {
  9. constexpr std::size_t MAX_BITS = 32 ;
  10. std::ostringstream stm ;
  11. stm << std::hex << std::bitset<MAX_BITS>( bits, 0, MAX_BITS ).to_ulong() ;
  12. return stm.str() ;
  13. }
  14.  
  15. // get the least significant 7 bits in a byte
  16. std::string seven_bits( const std::string& hex_byte )
  17. {
  18. std::istringstream stm(hex_byte) ;
  19. unsigned int b ;
  20. stm >> std::hex >> b ;
  21. return std::bitset<8>(b).to_string().substr(1) ;
  22. }
  23.  
  24. std::string uintvar_to_decimal( const std::string& uintvar )
  25. {
  26. constexpr std::size_t MAX_BITS = 64 ;
  27. const std::size_t NBYTES = std::min( uintvar.size()/2, MAX_BITS/8 ) ;
  28.  
  29. std::string bits ;
  30.  
  31. for( std::size_t i = 0 ; i < NBYTES ; ++i ) // for each byte
  32. bits += seven_bits( uintvar.substr( i*2, 2 ) ) ; // add the 7 lsb to bits
  33. std::ostringstream stm ;
  34. stm << std::bitset<MAX_BITS>(bits).to_ullong() ; // convert to decimal number
  35. return stm.str() ;
  36. }
  37.  
  38. int main()
  39. {
  40. const std::string bits = "1111111100010010001101001011" ;
  41. std::cout << binary_to_hex(bits) << '\n' ;
  42.  
  43. const std::string uintvar = "8a5c" ;
  44. std::cout << uintvar_to_decimal(uintvar) << '\n' ;
  45. }
  46.  
Success #stdin #stdout 0s 2992KB
stdin
Standard input is empty
stdout
ff1234b
1372