繁体   English   中英

如何将未签名的char *的内容转换为const char *?

[英]How do I convert the contents of an unsigned char * to a const char *?

我可以跨越重新解释的类型转换,并且在大多数情况下都会发出警告,因此我想知道是否还有其他选择(或者当然是重新解释的类型的干净实现)。

您没有说给出什么警告或问题是什么,但是在没有警告的情况下使用reinterpret_cast转换为char*应该可以:

unsigned char *a;
const char *b = reinterpret_cast<char*>(a);

这取决于您要执行的操作。

如果只想以char访问内容,则可以使用简单的static_cast或在期望使用char的上下文中使用该值来解决问题。

如果需要将缓冲区传递给需要char const* ,则reinterpret_cast是唯一的解决方案。

如果您想要一个字符串,可以使用指向缓冲区的指针:

std::string
bufferToString( unsigned char const* buffer, size_t length )
{
    return std::string( buffer, buffer + length );
}

或者您可以复制到现有字符串中:

myString.assign( buffer, buffer + length );
myString.append( buffer, buffer + length );
//  etc.

可以使用需要两个迭代器的任何字符串函数(或算法,例如std::copy )。 所需要做的就是解引用迭代器会导致类型隐式转换为char ,这是unsigned char的情况。

(您不能使用带有缓冲区地址和长度的字符串函数,因为它们不是模板,并且要求缓冲区地址具有char const*类型。而且, unsigned char隐式转换为charunsigned char*需要reinterpret_cast来将其转换为char* 。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM