I need this function for some personal work and although doing this in general is trivial, I haven’t really played around with bit-shifting before. I have the following code, which tries to convert an integer into a vector of unsigned integers, where each is 1 or 0 (representing the bit). I can assume that the integers are always greater than or equal to 0. Here is my code:
vector<unsigned int> toBinary(int x)
{
stack<unsigned int> s;
vector<unsigned int> ret_val;
for (unsigned i = 0; i < sizeof(x); ++i)
{
int z = ((x >> i) & 1) ? 1 : 0;
s.push(z);
}
unsigned num_bits = s.size();
for (unsigned i = 0; i < num_bits; ++i)
{
ret_val.push_back(s.top());
s.pop();
}
return ret_val;
}
This works okay for integers up to 16, then it fails. I use the stack to reverse the order of the bits so the most significant bit is on the left in the final returned value. Why is this broken, and how can I clean it up? Thank you
x is an int – presumably 32 bits, i.e. 4 bytes, in size. sizeof x = 4, 4 bits allow for numbers 0..15
What you want is 8*sizeof x, because of the 8 bits in a byte – although there is a better way (see below).
Cleaning up-wise:
Avoid
using namespace std, if you must use it then narrow it down to single use (e.g.using std::vector). This means decorating things withstd::, but it’s worth it for readability.Use
unsigned intrather thanint, be explicit about what you’re using.Returning a vector of
boolseems to make more sense.The number of bits in a unsigned int is given by
std::numeric_limits<unsigned int>::digits(#include <limits>).You can avoid the use of a stack easily enough by using
std::reverseon the vector (#include <algorithm>).Putting it all together, your function could look something like: