[removed] Need functions to convert a string containing binary to hex, then convert back to binary

前端 未结 4 890
醉梦人生
醉梦人生 2020-11-28 11:40

Lets say I have a string in JavaScript with binary data in it. It may look like this:

var binary = \'00001000010001000101010100001110\';

I

4条回答
  •  日久生厌
    2020-11-28 12:22

    Why not using Array.prototype.reduce?

    var binstr = "00001000010001000101010100001110"
    
    function bin2hex(b) {
        return b.match(/.{4}/g).reduce(function(acc, i) {
            return acc + parseInt(i, 2).toString(16);
        }, '')
    }
    
    function hex2bin(h) {
        return h.split('').reduce(function(acc, i) {
            return acc + ('000' + parseInt(i, 16).toString(2)).substr(-4, 4);
        }, '')
    }
    
    console.log(binstr);
    > 00001000010001000101010100001110
    console.log(bin2hex(binstr));
    > 0844550e
    console.log(hex2bin(bin2hex(binstr)));
    > 00001000010001000101010100001110
    

    Link to jsfiddle here.

    Notes:

    1. In bin2hex, if you want to convert also trailing chunks of less than 4 bits to hex, replace {4} with {1,4}. However, converting back the result to binary, will produce a string that differs from the original. For example, converting forth and back "111101" would produce "11110001".
    2. In hex2bin, binary values are left-padded with zeroes so as to have 4 binary digits for every hex digit.

提交回复
热议问题