Cody
Cody

Reputation: 8944

Why can't I typecast from char to int?

For some reason, the following code does not work:

char cValue = '8';
int digits = (int)cValue;

It keeps giving some value of 5 or 7, or something along those lines.

I'm just curious why - I'm using Character.getNumericValue(cValue); instead.

Why does this happen?

Upvotes: 3

Views: 5279

Answers (2)

Ryan Stewart
Ryan Stewart

Reputation: 128809

You can typecast char to int, and in fact you are. The binary representation of the character '8' is actually 56 (decimal). See any ASCII chart for the conversions. What you're looking for is parsing, not casting. getNumericValue() parses the char and gives you its numeric equivalent. Casting the char simply changes the type and leaves the pattern of bits the same. The bits are then interpreted according to the type of the variable they're associated with.

Upvotes: 6

Hot Licks
Hot Licks

Reputation: 47729

A Java char is an unsigned 16-bit value. When you cast one to int you get the Unicode value of the character. The character '8' has a Unicode value of decimal 56.

getNumericValue is entirely different -- it gives you the MEANING of the character, if it's a character with a numeric meaning.

Upvotes: 3

Related Questions