Emrah Akgül
Emrah Akgül

Reputation: 630

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 Bytes to a String without having any problems?

Upvotes: 2

Views: 9415

Answers (4)

Donald Raab
Donald Raab

Reputation: 6686

If you are open to using a third party library, the following solution works using Eclipse Collections:

MutableList<String> decryptedPasswordInPairs = Lists.mutable.with("A2")
    .collectWith((oddPair, A5) ->
            CharAdapter.adapt(oddPair)
                .injectIntoWithIndex(
                    ByteLists.mutable.empty(),
                    (bytes, character, index) ->
                        bytes.with((byte) (character ^ A5.charAt(index % A5.length()))))
                .makeString(""), "A5");
decryptedPasswordInPairs.each(System.out::println);

I used the following imports:

import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.factory.Lists;
import org.eclipse.collections.impl.factory.primitive.ByteLists;
import org.eclipse.collections.impl.string.immutable.CharAdapter;

By using the primitive ByteList available in Eclipse Collections, I was able to avoid boxing. The method makeString which is available on ByteList allows you to control the separator. Passing in an empty String gets rid of the comma that you get using toString on a List. The class CharAdapter provides a set of char based protocols around String including the method I used here named injectIntoWithIndex.

The code can also be broken into smaller steps to make it slightly less dense and potentially easier to read.

MutableList<String> decryptedPasswordInPairs = Lists.mutable.with("A2")
    .collect(CharAdapter::adapt)
    .collectWith((oddPair, A5) ->
        oddPair.injectIntoWithIndex(
            ByteLists.mutable.empty(),
            (bytes, character, index) ->
                bytes.with((byte) (character ^ A5.charAt(index % A5.length())))), "A5")
    .collectWith(ByteList::makeString, "");
decryptedPasswordInPairs.each(System.out::println);

Note: I am a committer for Eclipse Collections.

Upvotes: 2

Ramsay Domloge
Ramsay Domloge

Reputation: 705

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);
    }

Upvotes: 2

Sundararaj Govindasamy
Sundararaj Govindasamy

Reputation: 8495

Convert your list into array like below. Thanks @ bcsb1001

T[] toArray(T[] a)

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.

Byte[] byteArray = sample.toArray(new Byte[0])  

after that , You can create String from Byte array.

Use this constructor:

enter image description here

String str= new String(byteArray, "UTF-8");

Upvotes: -1

result is displayed as [0,7] instead of 07

This is because you are printing the list as a String.

You could get rid of that doing something like:

for (Byte b : sample) {
    System.out.print(b);
}

Or maybe, but not very elegant:

String result = sample.toString().replace(",", "").replace("[", "").replace("]", "");
decryptedPasswordInPairs.add(result);

Upvotes: 0

Related Questions