4

I'm looking for a straightforward answer and can't seem to find one.

I'm just trying to see if the following is valid. I want to take the integer 7 and turn it into the character '7'. Is this allowed:

int digit = 7;
char code = (char) digit; 

Thank you in advance for your help!

srsarkar7
  • 155
  • 5
  • 19

4 Answers4

4

This conversion is allowed, but the result won't be what you expect, because char 7 is the bell character whereas '7' is 55 (0x37). Because the numeric characters are in order, starting with '0' at 48 (0x30), just add '0', then cast the result as a char.

char code = (char) (digit + '0');

You may also take a look at the Unicode characters, of which the printable ASCII characters are the same codes.

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

'7' is Unicode code point U+0037.

Since it is a code point in the Basic Multiligual Plane, and since char is a UTF-16 code unit and that there is a one-to-one mapping between Unicode code points in this plane and UTF-16 code units, you can rely on this:

(char) ('0' + digit)

Do NOT think of '7' as ASCII 55 because that prevents a good understanding of char... For more details, see here.

fge
  • 119,121
  • 33
  • 254
  • 329
1

Nope. The char '7' can be retrieved from int 7 in these ways:

 int digit = 7;
 char code = Integer.toString(digit).charAt(0);
 code = Character.forDigit(digit, 10);
andy
  • 1,035
  • 1
  • 13
  • 35
0

If digit is between 0 and 9:

int digit = 7;
char code = (char)(((int)'0')+digit);
user2693979
  • 2,482
  • 4
  • 24
  • 23