【问题标题】:Convert unsigned char to string then again to unsigned char将 unsigned char 转换为字符串,然后再转换为 unsigned char
【发布时间】:2018-09-18 19:21:51
【问题描述】:

我要转换:

  1. 一个简单的unsigned char []string

  2. 然后再转为无符号字符

这是我的代码:

// This is the original char
unsigned char data[14] = {
    0x68,0x65,0x6c,0x6c,0x6f,0x20,0x63,0x6f,0x6d,0x70,0x75,0x74,0x65,0x72,
};

// This convert to string
string str(data, data + sizeof data / sizeof data[0]);

// And this convert to unsigned char again
unsigned char* val = new unsigned char[str.length() + 1];
strcpy_s(reinterpret_cast<char *>(val), str.length()+1 , str.c_str());

问题出在第二部分,它不会像以前那样将字符串转换为无符号字符。我认为this img from locals in debug 有帮助

【问题讨论】:

  • works。到底是什么问题?
  • val 确实包含data 的副本。 Visual Studio 的调试窗口只是没有将其显示为数组。如果您将val,14 添加到您的监视列表中,它将显示为一个数组。
  • @KompjoeFriek 谢谢我现在看到了,我想在某个地方使用val,它必须与data完全一样

标签: c++ converter unsigned-char


【解决方案1】:

一种方式:

#include <string>
#include <utility>
#include <cstring>
#include <memory>
#include <cassert>

int main()
{
    // This is the original char
    unsigned char data[14] = {
        0x68,0x65,0x6c,0x6c,0x6f,0x20,0x63,0x6f,0x6d,0x70,0x75,0x74,0x65,0x72,
    };

    // This convert to string
    std::string str(std::begin(data), std::end(data));

    // And this convert to unsigned char again
    auto size = std::size_t(str.length());
    auto new_data = std::make_unique<unsigned char[]>(size);
    std::memcpy(new_data.get(), str.data(), size);

    // check
    for (auto f1 = data, f2 = new_data.get(), e1 = f1 + size ; f1 != e1 ; ++f1, ++f2)
    {
        assert(*f1 == *f2);
    }
}

【讨论】:

  • 能否将data 复制到最后一部分的新无符号字符中?
  • 它给了我hello computerýýýý· 结果!奇怪
  • @AidenStewart 记住 new_data 不会被空终止。
  • C++11起“返回的数组是以null结尾的,即data()和c_str()执行相同的功能。”(来自en.cppreference.com/w/cpp/string/basic_string/data ),因此您可以将 size + 1 元素复制到空终止 new_data
  • @Bob__ 对。但是看看我从字符串中复制了多少个字符。复制的确切数字。您必须将 size 的值增加 1 以容纳并复制空终止符。
猜你喜欢
  • 2018-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-19
  • 2013-09-23
  • 1970-01-01
  • 1970-01-01
  • 2012-04-28
相关资源
最近更新 更多