Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get decimal ascii value of a char

I need to get a decimal ascii value of a char. Till now there was no problem to print it(avoiding negative values)using this.

char x;
cout << dec << (int)x << endl;

The problem comes when i want to assign the dec value to a int variable, dec cannot be used outside of the cout. Any suggestion how to do this? Note that (int) char wont work since I will get negative values as well and i want to avoid them.

I already tried with atoi and unsigned int, but so far, no luck.

like image 618
Capie Avatar asked Nov 01 '25 04:11

Capie


1 Answers

It is enough to cast an object of type char to an object of type unsigned char. For example

char c = CHAR_MIN; 

int x = ( unsigned char )c;

or

int x = static_cast<unsigned char>( c );
like image 137
Vlad from Moscow Avatar answered Nov 03 '25 21:11

Vlad from Moscow