2
votes

So, string comes with the value type of char. I want a string of value type unsigned char. Why i want such a thing is because i am currently writing a program which converts large input of hexadecimal to decimal, and i am using strings to calculate the result. But the range of char, which is -128 to 127 is too small, unsigned char with range 0 to 255 would work perfectly instead. Consider this code:

#include<iostream>
using namespace std;

int main()
{
    typedef basic_string<unsigned char> u_string;
    u_string x= "Hello!";

    return 0;
}

But when i try to compile, it shows 2 errors, one is _invalid conversion from const char* to unsigned const char*_ and the other is initializing argument 1 of std::basic_string<_CharT, _Traits, _Alloc>::basic_string...(it goes on)

EDIT: "Why does the problem "converts large input of hexadecimal to decimal" require initializing a u_string with a string literal?" While calculating, each time i shift to the left of the hexadecimal number, i multiply by 16. At most the result is going to be 16x9=144, which surpasses the limit of 127, and it makes it negative value. Also, i have to initialize it like this:

x="0"; x[0] -='0';

Because i want it to be 0 in value. if the variable is null, then i can't perform operations on it, if it is 0, then i can.

So, what should i do?

2
Why does the problem "converts large input of hexadecimal to decimal" require initializing a u_string with a string literal? - Robᵩ
@Robᵩ see my edit please. - user2653125
@user2653125 Your edit still doesn't explain why you need a string literal for initialisation. - Angew is no longer proud of SO
That doesn't answer my question. I mean, why do you care about initialization? - Robᵩ
Why use strings, anyway? What's wrong with std::vector<unsigned char>? - Angew is no longer proud of SO

2 Answers

3
votes

String literals are const char and you are assigning them to a const unsigned char.

Two solution you have:

First, Copy string from standard strings to your element by element.

Second, Write your own user-literal for your string class:

inline constexpr const unsigned char * operator"" _us(const char *s,unsigned int)
{
    return (const unsigned char *) s;
}

// OR 

u_string operator"" _us(const char *s, unsigned int len)
{
    return u_string(s, s+len);
}

u_string x = "Hello!"_us;
1
votes

An alternative solution would be to make your compiler treat char as unsigned. There are compiler flags for this:

  • MSVC: /J
  • GCC, Clang, ICC: -funsigned-char