1

Excuse me if this has been answered previously, but I can't seem to find an answer.

How do I convert a string of numbers (e.g "50") into a single char with an ASCII value of the same number, in this case '2'. Is there a way to do this conversion?

Alternatively, could I do the same by converting the string to an int first?

BladeMight
  • 2,670
  • 2
  • 21
  • 35
BvanW
  • 31
  • 5

2 Answers2

1

Here for some languages:

C/C++

int i = 65;
char c = i;
printf("%c", c); // prints A

JS

var c = String.fromCharCode(66);
console.log(c); // prints B

C#/Java

char c = (char)67;
// For Java use System.out.println(c)
Console.WriteLine(c) // prints C

Python

c = chr(68) # for Python 2 use c = str(unichr(68))
print(c) # Prints D
BladeMight
  • 2,670
  • 2
  • 21
  • 35
  • Mark as solved, by clicking on checkmark on left and upvote. – BladeMight Feb 04 '17 at 09:17
  • Even if the OP is happy that is not what he asks. He wanted to convert from a string that represents a number (e.g. "50") to ascii the character. You are converting from a number. – miracle173 Feb 04 '17 at 09:31
  • @miracle173 No problem, just use string to int converter and then what in my answer. – BladeMight Feb 04 '17 at 09:32
0
String s = "50";
try {
    char c = (char) Integer.valueOf(s);
    ... c
} catch (NumberFormatException e) {
    ...
}

With catching the NumberFormatException and checking the integer range the code might be made rock-solid.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138