Search code examples
javanode.jsarraysbytebuffer

Converting Java byte array to Buffer in Node.js


In an Android app I have a byte array containing data in the following format:

enter image description here

In another Node.js server, the same data is stored in a Buffer which looks like this:

enter image description here

I am looking for a way to convert both data to the same format so I can compare the two and check if they are equal. What would be the best way to approach this?


Solution

  • [B@cbf1911 is not a format. That is the result of invoking the .toString() method on a java object which doesn't have a custom toString implementation (thus, you get the default implementation written in java.lang.Object itself. The format of that string is:

    binary-style-class-name@system-identity-hashcode.

    [B is the binary style class name. That's JVM-ese for byte[].

    cbf1911 is the system identity hashcode, which is (highly oversimplified and not truly something you can use to look stuff up) basically the memory address.

    It is not the content of that byte array.

    Lots of java APIs allow you to pass in any object and will just invoke the toString for you. Where-ever you're doing this, you wrote a bug; you need to write some explicit code to turn that byte array into data.

    Note that converting bytes into characters, which you'll have to do whenever you need to put that byte array onto a character-based comms channel (such as JSON or email), is tricky.

    <Buffer 6a 61 ...>

    This is listing each byte as an unsigned hex nibble. This is an incredibly inefficient format, but it gets the job done.

    A better option is base64. That is merely highly inefficient (but not incredibly inefficient); it spends 4 characters to encode 3 bytes (vs the node.js thing which spends 3 characters to encode 1 byte). Base64 is a widely supported standard.

    When encoding, you need to explicitly write that. When decoding, same story.

    In java, to encode:

    import android.util.Base64;
    
    class Foo {
      void example() {
        byte[] array = ....;
        String base64 = Base64.encodeToString(array, Base64.DEFAULT);
        System.out.println(base64);
      }
    }
    

    That string is generally 'safe' - it has no characters in it that could end up being interpreted as control flow (so no <, no ", etc), and is 100% ASCII which tends to survive broken charset encoding transitions, which are common when tossing strings about the interwebs.

    How do you decode base64 in node? I don't know, but I'm sure a web search for 'node base64 decode' will provide hundreds of tutorials.

    Good luck!