-2

I have a program that reads from a file a set of characters and i need to transform this characters to their ascii representation.

En example of input is

'\n' '\0' 'a' 'b'

The input is comes from a file as a string and then is processed. To process the characters i use the getBytes() function from the string classand I don´t have any problem with regular characters ( a, b, ...), but with characters like \n getBytes method returns two ASCII values (the value from \ and the value from n).

How can I calculate the ASCII values of the whole string \n?

Oblivion
  • 1
  • 3
  • 1
    Does the input file contain a line *exactly* like it is in you question, including quotes and spaces? –  May 02 '15 at 17:21
  • 1
    Could you add the actual code? – Bubletan May 02 '15 at 17:22
  • This question looks similar: http://stackoverflow.com/questions/3537706/howto-unescape-a-java-string-literal-in-java – TMG May 02 '15 at 17:24
  • Yes, another example : `print 'h' 'e' 'l' 'l' 'o' '\n' ; ` Spaces and ; are skipped by the JFlex My actual code is the following `char[] cs = char.toCharArray(); return cs[0]; ` – Oblivion May 02 '15 at 17:24
  • 1
    And what if the characters are not in the ASCII set? E.g. `'ñ'`. – m0skit0 May 02 '15 at 17:25
  • 1
    If the character is not in the ASCII set i will throw an exception because this program doesn´t accept non-ascii characters – Oblivion May 02 '15 at 17:33

1 Answers1

2

make use of charAt method to get the character and find ASCII value of that particular character . beauty of charAt is it treats \n as single character .

int i;

    String sampleString="hello\nworld";
    for(i=0;i<sampleString.length();i++)
    System.out.println((int)sampleString.charAt(i));
Tirupati Rao
  • 615
  • 6
  • 24