Search code examples
javaandroidutf-8escapingoctal

Converting String consisting of octal numbers to UTF-8 text


Hello this is my first question on this site ever. I'm making a program that converts text to octal, but also octal to utf-8 text again.

150 145 154 154 157 40 167 157 162 154 144 should decode as hello world

Here is my code

source = source.replaceAll(" ", "");
int integer = Integer.parseInt(source,8);
List<Byte> queue = new LinkedList<>();
for (String s : source.split(" ")) {
    if (s != null && s != "") {
            for (byte b : s.getBytes()) {
                    queue.add(b);
            }
    }
}


Byte[] byteArr = new Byte[queue.size()];
byteArr = queue.toArray(byteArr);

byte[] b2 = new byte[byteArr.length];
for (int i = 0; i < byteArr.length; i++)
{
    b2[i] = byteArr[i];
}

String answer = new String(b2, StandardCharsets.UTF_8);
edittextbinary.setText(answer);

It just returns the same octal value and does not decode. I need help to extract the octal numbers and convert them to decimal and then decode to UTF-8


Solution

  • I hope this could help you.

    public static void main(String[] args) {
    
      String octalString = "150 145 154 154 157 40 167 157 162 154 144";
    
      StringTokenizer tokeniser = new StringTokenizer(octalString);
      int len = tokeniser.countTokens();
      int[] octalArray = new int[len];
      byte[] octalByteArray = new byte[len];
    
      for (int i = 0; tokeniser.hasMoreTokens(); i++) {
        octalArray[i] = Integer.parseInt(tokeniser.nextToken(),8);
        octalByteArray[i] = (byte) octalArray[i];
      }
      System.out.println(new String(octalByteArray, "UTF-8"));
    }