Superex
Superex

Reputation: 199

I do not understand char-to-int conversion

From page 72–73 of Programming: Principles and Practices using C++:

We saw that we couldn’t directly add chars or compare a double to an int. However, C++ provides an indirect way to do both. When needed, a char is converted to an int and an int is converted to a double. For example:

char c = 'x'; 
int i1 = c; 
int i2 = 'x'; 

Here both i1 and i2 get the value 120, which is the integer value of the character 'x' in the most popular 8-bit character set, ASCII. This is a simple and safe way of getting the numeric representation of a character. We call this char-to-int conversion safe because no information is lost; that is, we can copy the resulting int back into a char and get the original value:

char c2 = i1; 
  cout << c << ' << i1 << ' << c2 << '\n';

This will print x 120 x

I do not understand char-to-int conversion. I don't understand the stuff the author has said. Can you please help me?

Upvotes: 0

Views: 188

Answers (2)

Nick
Nick

Reputation: 10539

My 5 cents

Actually first one who thought about char to int conversion was Ada Lovelace (https://en.wikipedia.org/wiki/Ada_Lovelace).

When she discuss Analytical Engine (https://en.wikipedia.org/wiki/Analytical_Engine), she theorize that numbers could express letters and symbols and in this way, the Analytical Engine could theoretically process text information.

She even made some example "program" that works with text.

Upvotes: 0

Chris Tei
Chris Tei

Reputation: 316

The author is saying that you can safely convert from a char to an int for two reasons. The first is a char is single character represented by its ASCII value.

Here is the link to one such table http://www.asciitable.com/

As shown in the example, converting a 'x' to an int will result in 120, which is the decimal ASCII value for lowercase x.

The second reason this is safe to do, is because no variables are having their data changed or overwritten, since you are creating new variables for each conversion.

To sum it up, a char is a data type that represents an integer ASCII value as a character that corresponds with the given table, which is why you can easily convert from a char to an int, because they're essentially both integers.

Upvotes: 1

Related Questions