将long long数组转换为字符串

时间:2019-01-28 08:36:35

标签: c++ utf-8 binary

在c ++中 我有一个带符号的long long(63位数字)数组,一个可变长度数组。

std::array<long long, n> encodedString

此数组实际上包含一个UTF-8编码的字符串。这意味着,如果串联数组中每个元素的二进制文件,结果将是UTF-8编码的文本。

例如数组:

(621878499550 , 2339461068677718049) 

如果您将那些以63位二进制格式长时间签名的符号翻译为:

621878499550 = 000000000000000000000001001000011001010110110001101100011011110

2339461068677718049 = 010000001110111011011111110111001001101100011001000010000000100001

如果将这些二进制文件串联为: 000000000000000000000001001000011001010110110001101100011011110010000001110111011011110111001001101100011001000010000000100001

这是“ Hello world!”的UTF8。

所以问题是,使用“ Hello world!”获取字符串的最简单方法是什么?从数组开始(621878499550,2339461068677718049)

我目前最好的解决方案是将数组以二进制模式(fwrite)写入文件,然后以文本模式将文件读取为字符串。

2 个答案:

答案 0 :(得分:0)

尝试

// 48 & 56 were to avoid the extra padding made when you use 64 bitset but i think thats what you are looking for 
std::string binary = std::bitset<48>(114784820031264).to_string();
std::string binary2 = std::bitset<56>(2339461068677718049).to_string();
binary += binary2;
std::stringstream sstream(binary);
std::string output;
while (sstream.good())
{
    std::bitset<8> bits;
    sstream >> bits;
    output +=char(bits.to_ulong());

}

std::cout << output;

答案 1 :(得分:0)

使用位集将long long转换为二进制和字符串流以流式传输它们

#include <sstream>
#include <iostream>
#include <bitset>
#include <array>

int main() 
{
    std::array<long long, 2> array = { 621878499550 , 2339461068677718049ll };
    std::stringstream ss;

    for (auto& n : array)
    {
        ss << std::bitset<64>(n);
    }

    std::cout << ss.str() << std::endl;
}

输出0000000000000000000000010010000110010101101100011011000110111100010000001110111011011110111001001101100011001000010000000100001