Jan 15, 2017 at 1:10am UTC
I am writing a code that converts a non-negative number into a vector of binary numbers.
Example: 19 should become 10011 that is stored in a vector<bool>.
I am stuck because I don't even know what goes into the default constructor in the first place.
#include <iostream>
#include <vector>
class Integer
{
public:
Integer();
Integer(unsigned int a);
void print_as_int() const;
void print_as_bits() const;
private:
std::vector<bool> bit;
};
Integer::Integer()
{
bit[0] = 0;
}
Integer::Integer(unsigned int a) //you convert into bit here
{
if (a == 0) bit.push_back(0);
while (a > 0)
{
bit.push_back(a % 2);
a /= 2;
}
}
void Integer::print_as_bits() const
{
std::cout << "(";
for (int i = 0; i > bit.size(); i++)
{
std::cout << bit[i];
}
std::cout << ")_2";
}
int main()
{
unsigned int uint_value;
std::cout << "Please input an integer a: ";
std::cin >> uint_value;
Integer a = uint_value;
std::cout << "The base-2 representation of a is: ";
a.print_as_bits();
std::cout << std::endl;
return 0;
}
Last edited on Jan 15, 2017 at 1:10am UTC
Jan 15, 2017 at 4:29am UTC
Item 18, Effective STL (Scott Meyers): Avoid using vector<bool>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include <iostream>
#include <string>
#include <deque>
#include <limits>
using numType = unsigned long long ;
struct NumberToBinary
{
numType m_num;
std::deque<bool > m_binary_rep;
NumberToBinary(const numType& num) : m_num(num)
{
const numType base = 2;
std::string s;
s.reserve( std::numeric_limits<numType>::digits );
do { s.push_back( m_num % base + '0' ); } while ( m_num /= base );
for (auto & elem : s)
{
elem == '1' ? m_binary_rep.push_front(true ): m_binary_rep.push_front(false );
}
}
};
int main()
{
NumberToBinary x(19);
for (auto & elem : x.m_binary_rep)
{
std::cout << elem << " " ;
}
}
edit: add some input validation for negative numbers, etc of course
Last edited on Jan 15, 2017 at 6:20am UTC