Sidebar

How to convert strings to byte[] and back again

0 votes
1.6K views
asked Mar 5, 2014 by rich-c-2789 (17,490 points)

1 Answer

0 votes
 
Best answer

 

See the comments in the code below for an explanation:

//Create a Java string
var example = new java.lang.String('This is plain text');


//Convert String to bytes. This method is only available on Java strings. Not JavaScript strings.
var bytes = example.getBytes();

qie.debug("Output plain text: " + example);
qie.debug("Output as bytes: " + bytes);

//Try to convert bytes to string. This does not convert it back to the original text.
qie.debug("Output result of calling toString() on bytes: " + bytes.toString());

//Convert bytes to string. This is the correct way to convert the byte[] to the original text.
var s = new java.lang.String(bytes);
qie.debug("Output converting bytes back to text : " + s);

Here are the results of executing the above code:

Output plain text: This is plain text

Output as bytes: [B@68a394

Output result of calling toString() on bytes: [B@68a394

Output converting bytes back to text : This is plain text

answered Mar 5, 2014 by rich-c-2789 (17,490 points)
selected Dec 26, 2014 by sam-s-1510
commented Jun 15, 2019 by ryan-w-6043 (460 points)
edited Jun 15, 2019 by ryan-w-6043
This works fine for text strings but does not work for binary data. I have a PDF file that I am receiving via HL7 as b64 that I need to send via API as an unencoded string (needs to be sent just like it looks opening the file in notepad). After i b64 decode to byte and run this on the byte array:
var aBytes = qie.base64DecodeToBytes(b64Pdf);
var s = new java.lang.String(aBytes);
var bBytes = s.getBytes();
qie.debug(java.util.Arrays.equals(aBytes, bBytes)); //Returns FALSE

If I write aBytes to file I can open the PDF. If I write bBytes to file there are extra ? in the binary data and the file isn't able to be opened. Same thing if I b64 decode to string and then convert to byte[] and write the file.  I believe it has something to do with java bytes being signed.

EDIT:
Looks like binary data requires setting a different encoding that is 1 to 1 mapping.
This works:
var s = new java.lang.String(aBytes, "ISO-8859-1");
bytes = s.getBytes("ISO-8859-1");
...