fork download
  1. #include <iostream>
  2. #include <bitset>
  3. using namespace std;
  4. typedef unsigned short uint16_t;
  5. typedef short int16_t;
  6. #define CHAR_BIT 8
  7.  
  8. template <typename T,size_t count> static T convertBitSetToNumber( const std::bitset<count>& bitset )
  9. {
  10. T result;
  11. #define targetSize (sizeof( T )*CHAR_BIT)
  12. if ( targetSize > count )
  13. {
  14. // if bitset is 0xF00, converting it as 0x0F00 will lose sign information (0xF00 is negative, while 0x0F00 is positive)
  15. // This is because sign bit is on the left.
  16. // then, we need to add a zero (4bits) on the right and then convert 0xF000, later, we will divide by 16 (2^4) to preserve sign and value
  17.  
  18. size_t missingbits = targetSize - count;
  19.  
  20. std::bitset<targetSize> extended;
  21. extended.reset(); // set all to 0
  22. for ( size_t i = 0; i != count; ++i )
  23. {
  24. if ( i < count )
  25. extended[i+missingbits] = bitset[i];
  26. }
  27.  
  28. result = static_cast<T>( extended.to_ullong() );
  29.  
  30. int mask = 1 << (targetSize-missingbits-1);
  31. mask |= mask - 1;
  32.  
  33. result = result >> missingbits;
  34. result = result & mask;
  35.  
  36. return result;
  37. }
  38. else
  39. {
  40. return static_cast<T>( bitset.to_ullong() );
  41. }
  42. }
  43.  
  44. int main() {
  45. uint16_t val1 = convertBitSetToNumber<uint16_t,12>( std::bitset<12>( "100010011010" ) );
  46. // val1 is 0x089A
  47. int16_t val2 = convertBitSetToNumber<int16_t,12>( std::bitset<12>( "100010011010" ) );
  48.  
  49. cout << std::hex << val1 << endl;
  50. cout << std::hex << val2 << endl;
  51. return 0;
  52. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
89a
89a