【问题标题】:convert array of long long into string将 long long 数组转换为字符串
【发布时间】:2019-06-21 05:27:41
【问题描述】:

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

std::array<long long, n> encodedString

这个数组实际上保存了一个 UTF-8 编码的字符串。这意味着如果你连接数组中每个元素的二进制文件,结果将是一个 UTF-8 编码的文本。

例如数组:

(621878499550 , 2339461068677718049) 

如果你将那些有符号的 long long 翻译成 63 位二进制,它会给出:

621878499550 = 000000000000000000000001001000011001010110110001101100011011110

2339461068677718049 = 010000001110111011011110111001001101100011001000010000000100001

如果您将这些二进制文件连接到: 000000000000000000000000100100001100101011011000110110001101111001000000111011101101111011100100110110001100100001000000100010001

这是“Hello world!”的 UTF8 编码

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

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

【问题讨论】:

  • 请注意,signed long long 仍然是 64 位(至少)。
  • 将数组写入字符串流而不是文件。然后你有相同的操作,但完全在内存中,而不是使用外部文件。
  • 至于您的问题,您需要将数据放入一个字节数组(即基本上是char 的数组)。然后跳过前导零字节。然后您可以将剩余的数据复制到std::string。使用中间char 缓冲区确实是唯一不受the strict aliasing rule 困扰的方法。
  • 是的,你是对的,它仍然是 64 位,所以我需要去掉符号位。
  • 您的样本数组的两个元素具有相同的值。这转化为' world ! world !'

标签: c++ utf-8 binary


【解决方案1】:

使用 bitset 将 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

【讨论】:

  • 感谢您的回复。但是我需要的是输出字符串“Hello world!”,而不是二进制字符串。有什么想法吗?
【解决方案2】:

试试这个

// 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;

【讨论】:

  • 感谢您的回复。但是,我需要将字符串“Hello world!”作为输出,这会将二进制序列输出为字符串。有什么想法吗?
猜你喜欢
  • 2020-12-02
  • 2016-04-06
  • 1970-01-01
  • 2010-12-31
  • 2023-03-22
  • 2013-11-25
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多