I have a string variable containing 32 bits of binary. What would be the best way to convert these 4 characters (8 bits is one character) represented by the binary back into the
here is my attempt:
std::string str2bits(const std::string_view &str, bool big_endian = false)
{
std::string ret;
ret.reserve(str.size() * 8);
for (size_t i = 0; i < str.length(); ++i)
{
const uint8_t ord = uint8_t(str[i]);
for (int bitnum = (big_endian ? 0 : 7);; (big_endian ? (++bitnum) : (--bitnum)))
{
if ((big_endian && bitnum >= 8) || (!big_endian && bitnum < 0))
{
break;
}
if (ord & (1 << bitnum))
{
ret += "1";
}
else
{
ret += "0";
}
}
}
return ret;
}
str2bits("test") ==> 01110100011001010111001101110100