0

This message is coming from external system and this is coming as bytes, I have to use it in my Java code. I am taking it as a byte and converting to String.

Can anyone help me to accept it as byte only instead of taking it to string and converting to byte.

Here is the output from that external system till equals to:

wcLDxMXGx8jJ0fHy8/T1AHsSNFw=

I want to store it either in byte or byte[].

I have tried doing it myself but it says error at =. I have to use it as byte only as taking it as String and then converting to byte will be problematic and not as expected.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
user3930361
  • 181
  • 1
  • 1
  • 9

2 Answers2

1

You can use the class javax.xml.bind.DatatypeConverter (since Java SE 6 update 3):

Code:

public static void main(String[] args) {
    String str = "wcLDxMXGx8jJ0fHy8/T1AHsSNFw=";
    byte[] array = DatatypeConverter.parseBase64Binary(str);
    System.out.println(Arrays.toString(array));
}

Output:

[-63, -62, -61, -60, -59, -58, -57, -56, -55, -47, -15, -14, -13, -12, -11, 0, 123, 18, 52, 92]
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
0
try (ByteArrayInputStream bais = new ByteArrayInputStream()) {
    try (InputStream externalSource = ...)) {
        for (;;) {
            int b = externalSource.read();
            if (b == -1 || b == 'I') { // End of file or ASCII I
                break;
            }
            bais.write((byte) b);
        }
    }
    byte[] bytes = bais.toByteArray();
}

There is a "till" in your question, which I translated into a condition || b == 'I'. You probably did not intend that. Maybe you used = instead of ==.

The above reads an int which is -1 when end-of-file, a byte value otherwise.

The try-with-resources syntax ensures that externalSource and bais are closed.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138