I am interested in understanding the implementation of converting decimal to binary. Could somebody clarify the purpose of using left-shift and Right-shift in the following code?
void static inline unsignedToBinary(unsigned x, char*& bin)
{
bin = (char*) malloc(33);
int p = 0;
for (unsigned i = (1 << 31); i > 0; i >>= 1)
bin[p++] = ((x&i) == i) ? '1' : '0';
bin[p] = '\0';
}
This is a straightforward implementation of binary conversion that uses bit operations.
i
represents the mask - an int
containing 2k value, where k
is the position of the bit.1
by 31.for
loop uses >>= 1
to right-shift the mask until 1
gets shifted out of it, making i == 0
.x&i
is compared to i
. The comparison succeeds when x
contains 1
in the position where i
has its 1
; it fails otherwise.Note: Although using malloc
in C++ is certainly allowed, it is not ideal. If you want to stay with C strings, use new char[33]
instead. A more C++-like approach would be using std::string
.