Convert a string of binary into an ASCII string (C++)

前端 未结 4 853
我在风中等你
我在风中等你 2021-02-05 23:19

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

4条回答
  •  忘掉有多难
    2021-02-05 23:33

    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

提交回复
热议问题