char takes values in the range of -128 to 127. By simply putting unsigned before char the range changes to 0-255.
How to achieve the same effect in a string? So that all chars in that string take values from 0-255?
-
1Simply cast it (at character element level)!πάντα ῥεῖ– πάντα ῥεῖ2013-09-15 00:48:40 +00:00Commented Sep 15, 2013 at 0:48
-
@g-makulik can you be more specific by what you mean with 'casting the string'? Can't find anything useful on google about that.user2653125– user26531252013-09-15 00:51:15 +00:00Commented Sep 15, 2013 at 0:51
-
1@user2653125 g-makulik was not speaking about casting a string, but just a single character. See my answer.syam– syam2013-09-15 00:53:25 +00:00Commented Sep 15, 2013 at 0:53
Add a comment
|
1 Answer
chartakes values in the range of -128 to 127.
No.
char is implementation-defined, it could be either signed char or unsigned char depending on what your compiler chose to use. And char doesn't necessarily means byte BTW... (there are some platforms where a char is 16 bits for example)
If you want to ensure that a char is indeed an unsigned char then just cast it: static_cast<unsigned char>(some_char_value)
11 Comments
user2653125
thanks, but where should i put this line of code? and does it affect STRINGS, because there is where i am interested in..
syam
@user2653125 Strings are just a series of characters, it's really not that hard once you stop and think about it for a few seconds. As to where you should put this line of code, you didn't show any of your own code so I can't tell. The idea is: wherever you use a
char and want to ensure the value is unsigned, then you should use it.user2653125
here for example: #include<iostream> using namespace std; int main() { string x="Hello"; x[3]=150; cout<<int(x[3]); return 0; }
syam
@user2653125
cout << (int)static_cast<unsigned char>(x[3]);Keith Thompson
Type
char has the same size and representation as either signed char or unsigned char, but they're still three distinct types. |