1

I am trying to read the ASCII value of bytes in the inputstream. I have the following code

 int bd = 0;
 byte[] buffer = new byte[260];
 while (true) {
     try {
          if ((bd = inputStream.read(buffer, 0, buffer.length)) > 0) {
              Log.d("TAG", "Number of bytes from stream" + bd);
           }

In order to read the value of bytes. I tried one of the following method from this SO example read byte value.

String s = new String(buffer,StandardCharsets.US_ASCII);

System.out.println("data from buffer s : " + s);
Result of s:"/9AAAAAAAAAAAAA=="
System.out.println("data from buffer s : " + parseInt(s)); -- error

String s2 = new String(buffer);
System.out.println("data from buffer s2: " + s2);
Result of s2: �@���������������

How can I get the ASCII values which are int ? I tried to convert string into Int using parseInt(s) but I get thrown into NumberFormatException error

cantona_7
  • 1,127
  • 4
  • 21
  • 40
  • you want a byte value as int (in an `int` variable)? you want the int value that corresponds to 4 bytes? ...? maybe some example in terms of input value and expected output could help – user85421 Jul 31 '19 at 13:14
  • @CarlosHeuberger I would like to get the ascii values – cantona_7 Jul 31 '19 at 13:15
  • like: *I have, for example, a String `"/A" and want the respective ASCII values `int[] { 47, 65 }` .* ? – user85421 Jul 31 '19 at 13:20
  • yes I am looking for that. But the conversion leads to `NumberFormatexception error` – cantona_7 Jul 31 '19 at 13:21
  • 2
    then I didn't understand the "*bytes in the inputstream*" part?? nor the base 64 one? you can get each `char` of the String (`toCharArray()` or `charAt()`) which are actually the code of that character and be cast to `int`(`char ch = ...; int ascii = (int) ch;`) – user85421 Jul 31 '19 at 13:26

2 Answers2

2

How can I get the byte values which are int ?

Convert int to string first

 int a = 454545454;
        String data = String.valueOf(a);
        try {
            byte[] bytesdata = data.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

on your question change

Replace all non-digit with blank: the remaining string contains only digits.

Integer.parseInt(s.replaceAll("[\\D]", ""))

Now for further have look Get ASCII from int

Hemant Parmar
  • 3,924
  • 7
  • 25
  • 49
1

what are you trying to do here? print only the number 9 from the given string? if so you can catch the number format exception and handle it.

or are you trying to print that ascii code for the string "/9AAAAAAAAAAAAA=="?

As Carlos said above, if you have each char in the loop, just cast it to an int and you will get the underlying value in memory.

    char b1 = 'f';
    System.out.println("data from buffer s2: " + (int) b1);


    "data from buffer s2: 102"
tmc
  • 404
  • 1
  • 7
  • 20