1

I am modding a java program and in it a handler receives 2 byte arrays When I print those arrays using a line of code like this\

java.util.Arrays.toString(this.part1))

I get an output like this

[43, 83, 123, 97, 104, -10, -4, 124, -113, -56, 118, -23, -25, -13, -9, -85, 58, -66, -34, 38, -55, -28, -40, 125, 22, -83, -72, -93, 73, -117, -59, 72, 105, -17, 3, -53, 121, -21, -19, 103, 101, -71, 54, 37...

I know these byte arrays contain a string. How might I get that string from them? Here is the code

    public void readPacketData(PacketBuffer data) throws IOException
{
    this.field_149302_a = data.readByteArray();
    this.field_149301_b = data.readByteArray();
    String packet1 = (java.util.Arrays.toString(this.field_149302_a));
    String packet2 = (java.util.Arrays.toString(this.field_149301_b));

}
2

3 Answers 3

1

In order to convert Byte array into String format correctly, we have to explicitly create a String object and assign the Byte array to it. You can try this:

String str = new String(this.part1, "UTF-8"); //for UTF-8 encoding
System.out.println(str);

Please note that the byte array contains characters in a special encoding (that you must know).

Sign up to request clarification or add additional context in comments.

2 Comments

+w?çP"aâ±ÊC³„JÜ—Ó¹vÈÚ Ð­x<Z¾^xýºonOB¥Ùâ‚-ô€AœJ¤ÄEfûÑ6øŠAŠ?I˜XmZQÄe—YÖêÛ".• qìr½sa$2±n}*™¥iÛd„×7NæmfG–".˜AÎÅó
This is what it outputs for some reason
0

String has a constructor from byte[], so you could just call new String(this.part1), or, if the bytes do not represent a string in the platform's default charster, use the overloaded flavor and pass the charset too.

Comments

0

actually to convert bytes to String you need encoding name. You need to change UTF-8 to correct encoding name in first answer to avoid wrong output, try UTF-16 or one of https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html (try to choose by your locale).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.