0

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?

3
  • 1
    Simply cast it (at character element level)! Commented 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. Commented 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. Commented Sep 15, 2013 at 0:53

1 Answer 1

1

char takes 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)

Sign up to request clarification or add additional context in comments.

11 Comments

thanks, but where should i put this line of code? and does it affect STRINGS, because there is where i am interested in..
@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.
here for example: #include<iostream> using namespace std; int main() { string x="Hello"; x[3]=150; cout<<int(x[3]); return 0; }
@user2653125 cout << (int)static_cast<unsigned char>(x[3]);
Type char has the same size and representation as either signed char or unsigned char, but they're still three distinct types.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.