Search code examples
javascriptendianness

Convert a binary string to big endian integer in the browser?


I have the following string in binary :

const bin = '\x00\x00\x16%'

I'd like to convert it in big endian integer.

I was able to do it using the following:

new DataView(Uint8Array.from('\x00\x00\x16%', c => c.charCodeAt(0)).buffer).getInt32(0, false)
=> 5669

But I'm pretty sure there is asimpler way to do so, rather than convert to an Uint8Array and then pass it to a dataview.

(Note: This is for browser only, not Node.js. I saw all the SO post about Buffer.readUIntBE, but they aren't native to the browser.)


Solution

  • function bin2int(bin) {
                var i = 0;
                var len = bin.length;
                var num = 0;
                while (i < len) {
                    num <<= 8;
                    num += bin.charCodeAt(i);
                    i++;
                }
                return num;
            }
    

    This works on the browser and yields the same result. May not be as simple as you'd like it to though