Caffeinated
Caffeinated

Reputation: 12484

In Java, how would I convert from ASCII codes into their integers?

Suppose I have a byte array of integers. How would I go from those ASCII codes back to the real-world integers?

For example, if we read a simple text file of integers , like so :

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

...into a byte array, like this one :

boolean empty = true;
while (( readChars = is.read(c)) != -1) {
  for (int i = 0; i < readChars; ++1) {
    Byte b = c[i];
    int xx = b.intValue();
    lastLine = xx;

    if (c[i] == '\n'){
      ++count;
      empty = true;
    } else {
        empty = false;
    }

  }
  }
  if (!empty) {
    count++;  
  }

Then once that file (which was just normal integers) gets put into the byte array.. if we then try to print it back to the screen again, it won't get print as number 5 , but as the ASCII code -which is 53

Just trying to wrap my head around this encoding topic, any tips appreciated thanks

thanks

Upvotes: 0

Views: 57

Answers (2)

Jemo Mgebrishvili
Jemo Mgebrishvili

Reputation: 5487

try this :

int asciiValue = 53;
int numericValue = Character.getNumericValue(asciiValue);

System.out.println(numericValue);

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201467

You can cast from char to int. Something like,

char[] chars = "12345".toCharArray();
for (char ch : chars) {
    System.out.printf("%c = %d%n", ch, (int) ch);
}

Output is

1 = 49
2 = 50
3 = 51
4 = 52
5 = 53

Upvotes: 2

Related Questions