繁体   English   中英

强制std :: string使用unsigned char(0到255)而不是char(-128到127)

[英]Force std::string to use unsigned char (0 to 255) instead of char (-128 to 127)

有没有办法强制字符串使用unsigned char而不是char? 也许在构造函数中?

我需要进行算术运算(主要是递增,递减,〜(按位NOT)),我需要能够使用溢出255 ++ == 0 ...不是127 ++ == -128(和下溢0- - == 255 ...)

我不确定问题是否有意义,在这里说一下这是一个很好的问题(流) 为什么C ++流使用char而不是unsigned char?

我没有尝试将字符串转换为unsigned char我发现很多问题如何在两者之间进行转换。

您可以使用:

typedef std::basic_string<unsigned char> ustring;

然后使用ustring而不是std::string

std::string实际上只是一个std::basic_string<char>

你需要的是一个std::basic_string<unsigned char>

这个SO线程这个答案中有一些很好的转换方法

#include <string>
#include <iostream>

typedef std::basic_string<unsigned char> ustring;

inline ustring convert(const std::string& sys_enc) {
  return ustring( sys_enc.begin(), sys_enc.end() );
}

template< std::size_t N >
inline ustring convert(const char (&array)[N]) {
  return ustring( array, array+N );
}

inline ustring convert(const char* pstr) {
  return ustring( reinterpret_cast<const ustring::value_type*>(pstr) );
}

std::ostream& operator<<(std::ostream& os, const ustring& u)
{
    for(auto c : u)
      os << c;
    return os;
}

int main()
{
    ustring u1 = convert(std::string("hello"));
    std::cout << u1 << '\n';

    // -----------------------
    char chars[] = { 67, 43, 43 };
    ustring u2 = convert(chars);
    std::cout << u2 << '\n';

    // -----------------------
    ustring u3 = convert("hello");
    std::cout << u3 << '\n';
}

coliru

只需使用:

std::vector<unsigned char> v;

暂无
暂无

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

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