Advertisement
Guest User

Untitled

a guest
Feb 27th, 2015
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #undef __STRICT_ANSI__
  2.  
  3. #include <iostream>
  4. #include <algorithm>
  5. #include <string>
  6. #include <vector>
  7.  
  8. using namespace std;
  9.  
  10. typedef signed long long int int64;
  11.  
  12. #define all(a) (a).begin(), (a).end()
  13.  
  14. template<typename T> inline unsigned int getBitsInType() {
  15.   static const unsigned int bitsInByte = 8;
  16.   return bitsInByte * sizeof(T);
  17. }
  18.  
  19. template<typename T> inline bool isTrueBit(const T &number, const int &bitIndex) {
  20.   return number & ((T)1 << bitIndex);
  21. }
  22.  
  23. template<typename T> string binaryRepresentation(const T &number) {
  24.   unsigned int bits = getBitsInType<T> ();
  25.  
  26.   string binary(bits, '0');
  27.   for (int i = 0; i < bits; ++i) {
  28.     if (isTrueBit(number, i)) {
  29.       binary[i] = '1';
  30.     }
  31.   }
  32.  
  33.   while (binary.size() > 1 && binary.back() == '0') {
  34.     binary.pop_back();
  35.   }
  36.  
  37.   reverse(all(binary));
  38.   return "b" + binary;
  39. }
  40.  
  41. template<typename T> vector<unsigned int> listOfSetBits(const T &number) {
  42.   unsigned int bits = getBitsInType<T> ();
  43.  
  44.   vector<unsigned int> listOfBits;
  45.   for (int i = 0; i < bits; ++i) {
  46.     if (isTrueBit(number, i)) {
  47.       listOfBits.push_back(i);
  48.     }
  49.   }
  50.  
  51.   return listOfBits;
  52. }
  53.  
  54. int main() {
  55.   int64 n;
  56.   cin >> n;
  57.   cout << binaryRepresentation(n) << endl;
  58.  
  59.   for (int index : listOfSetBits(n)) {
  60.     cout << index << endl;
  61.   }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement