Search code examples
c++type-conversioncharasciioverflow

Section character (§) overflows char type (C++)


When trying to define the char:

char q = '§';

clion throws an error: "Character too large for enclosing character literal type". This is weird as if I look up the ascii conversion of § it is just 167.

If I use:

char c;
std::string q = "§";
for (char el:q) {
    c = el;
    std::cout << c;
}

the output reads: §

and:

int c;
std::string q = "§";
for (char el:q) {
    c = (int) el;
    std::cout << c;
}

outputs: -62-89

So it seems that the character overflows the char type

I am implenting RSA encryption using unsinged long long int instead of int in this case and the overflow still occurs which corrupts the decrypted data. How can I convert this character and potentially others that may overflow the char type into their respective ascii value (for this example (char)'§' should return 167).

conversion with unsigned long long int:

#define ull unsigned long long int

int main() {
    ull c;
    std::string q = "§";
    for (char el:q) {
        c = (ull) el;
        std::cout << c;
    }

}

output: 1844674407370955155418446744073709551527

using wchar_t also did not fix the issue.


Solution

  • One way to go around it is to use unicode string:

    auto q = u"\u00A7";
    

    Unicode strings (u for 16-bit and U for 32-bit) can in general be used similarly to normal std::string type but when you iterate over it or index into it, you'll have the corresponding character type: char16_t or char32_t.