【问题标题】:How to convert from 'const char [9]' to 'const unsigned char *'如何从 'const char [9]' 转换为 'const unsigned char *'
【发布时间】:2013-09-29 23:38:16
【问题描述】:

我正在尝试代码mentioned here:

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
}

然后通过:base64_encode("mystring", 8)。

显示类型转换错误:

错误 C2664:“base64_encode”:无法将参数 1 从“const char [9]”转换为“const unsigned char *”

【问题讨论】:

  • 我认为你的主要问题是 unsigned char const* 尝试让它成为 char*
  • 您的字符串文字是一个字符数组,而不是一个无符号字符数组。您要么需要转换它,要么使用 unsigned char 数组作为输入。
  • 我不明白为什么它首先是一个“const”。但它现在似乎工作了。

标签: c++


【解决方案1】:

我刚刚看到这篇文章,想为其他尝试对字符串进行 base64 编码的人澄清一下。原帖所指代码来自网页:http://www.adp-gmbh.ch/cpp/common/base64.html。如果您转到作者的页面并查看“测试文件”部分,您将确切地看到作者如何推荐要使用的代码。

const std::string s = "test string" ;
std::string encoded = base64_encode(reinterpret_cast<const unsigned char*>(s.c_str()), s.length());

我在我的程序中尝试过,它似乎工作得很好。

【讨论】:

    【解决方案2】:

    我认为你不能使用unsigned chars 来获得字符串文字。从字符串文字创建unsigned chars 序列的最简单方法可能是

    char const* literal = "hello";
    std::vector<unsigned char> ustr(literal, literal + std::strlen(literal));
    unsigned char const* ustrptr = ustr.data();
    

    显然,该逻辑可以封装成一个合适的函数调用base64_encode()。

    替代方案是 reinterpret_cast&lt;unsigned char const*&gt;("hello"),但我个人不是这种方法的忠实拥护者。

    【讨论】:

    • 我认为 Zack Newsham 的解决方案更优雅。 C++ 可能看起来有点难看,因为这样的东西:“std::vector ustr(literal, literal + std::strlen(literal)); unsigned char const* ustrptr = ustr.data();”你为什么不喜欢:reinterpret_cast("hello")?
    • 我觉得unsigned char x[] = "hello";也是可以的,见[dcl.init.string]/1。
    • 除了reinterpret_cast之外,你不喜欢的铸造解决方案呢?复制字符串以执行本质上是强制转换的操作似乎很浪费?
    • 另一种演员风格的解决方案是using uchar_arr = unsigned char const[]; bae64_encode(uchar_arr{"hello"});。
    • @Troy:reinterpret_cast&lt;...&gt;() 的行为通常是实现定义的。由于我的代码适用于我什至不知道的平台,因此使用任何实现定义的东西都是有问题的。虽然转换方法可能会带来一些开销,但它是可移植的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多