Kyslik
Kyslik

Reputation: 8385

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

Is there a way to force string use unsigned char instead of char? Perhaps in constructor?

I need to do arithmetic operations (mostly incrementing, decrementing, ~ (bitwise NOT)), and I need to be able to use overflow 255++ == 0... Not 127++ == -128 (and underflow 0-- == 255...)

I am not sure if question makes sense, to put some light on it here is a good question abou topic (streams) Why do C++ streams use char instead of unsigned char?

I am not trying to convert string to unsigned char I found a lot of questions how to convert between the two.

Upvotes: 3

Views: 1475

Answers (3)

Patryk
Patryk

Reputation: 24150

std::string in reality is just a std::basic_string<char>

What you need is a std::basic_string<unsigned char>

There are some nice conversion methods in this answer from this SO thread

#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

Upvotes: 4

Paul Evans
Paul Evans

Reputation: 27577

Simply use a:

std::vector<unsigned char> v;

Upvotes: 1

Mohit Jain
Mohit Jain

Reputation: 30489

You can use:

typedef std::basic_string<unsigned char> ustring;

And then use ustring instead of std::string

Upvotes: 5

Related Questions