Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading