4

I'm having trouble sending data from Java to Javascript and the reverse of that.

Ive tried this so far:

//a function I found online I use it to convert the decoded version of the java base64 byte[] to an ArrayBuffer
    function str2ab(str) {
      var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
      var bufView = new Uint16Array(buf);
      for (var i=0, strLen=str.length; i<strLen; i++) {
        bufView[i] = str.charCodeAt(i);
      }
      return buf;
    }

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));//retuns a different value than what I put into the buffer.
}

I really don't know how to go about this anymore any ideas?

1 Answer 1

6

Java

using import com.sun.org.apache.xml.internal.security.utils.Base64;

byte[] b = new byte[] { 12, 3, 4, 5, 12 , 34, 100 };
String encoded = Base64.encode(b);

produces:

"DAMEBQwiZA=="

JavaScript

use atob and btoa

var stringToByteArray = function(str) {
    var bytes = [];
    for (var i = 0; i < str.length; ++i) {
        bytes.push(str.charCodeAt(i));
    }
    return bytes;
};
var decoded = stringToByteArray(atob("DAMEBQwiZA=="));

produces:

[ 12, 3, 4, 5, 12 , 34, 100 ]

Note: If you are doing this in NodeJS then take a look at the atob package.

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

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.