Emrah Akgül Emrah Akgül - 5 months ago 10
Java Question

Convert List<Byte> to string

I have the following code:

List<String> decryptedPasswordInPairs = new ArrayList<String>();
String A5 = "A5";
for (String oddPair : oddPairsInEncryptedPassword) {
List<Byte> sample = new ArrayList<>();
for (int i = 0; i < oddPair.length(); i++) {
byte x = (byte) (oddPair.charAt(i) ^ A5.charAt(i % A5.length()));
sample.add(x);
}
String result = sample.toString();
decryptedPasswordInPairs.add(result);
}


In this code,
result
is displayed as
[0,7]
instead of
07
when I debug the program to check the value of
result
.

Is there a way to convert this
List
of
Byte
s to a
String
without having any problems?

Answer

In this solution, I collect the characters in a StringBuilder and convert to a String at the end:

List<String> decryptedPasswordInPairs = new ArrayList<String>();
    String A5 = "A5";

    List<String> oddPairsInEncryptedPassword = new LinkedList<String>();
    oddPairsInEncryptedPassword.add("A2");

    for (String oddPair : oddPairsInEncryptedPassword) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < oddPair.length(); i++) {
            byte x = (byte) (oddPair.charAt(i) ^ A5.charAt(i % A5.length()));
            sb.append(""+x);
        }

        String result = sb.toString();
        System.out.println(result);
        decryptedPasswordInPairs.add(result);
    }