When I was trying to iterate a number (transformed to binary with bitset library) I managed this solution
#include <iostream>
#include <bitset>
void iterateBinary(int num) {
char *numInBinary = const_cast<char*>(std::bitset<32>(num).to_string().c_str());
for (int i = 31; i >= 0; i--) {
char bit = numInBinary[i];
std::cout << i << ": " << bit << std::endl;
}
}
But founded those weird characters in the output
I already implemented a solution to my initial idea with for (char bit : numInBinary)
and without c_str()
transformation, but I'm still curious about what happened (maybe memory problems?) or which can be a better way to iterate a char*
string
Also remark that the "corrupt" values in the output are no the same on each ejecution and only appears at the end, why? Thanks in advance