开发者

How to write a base32_decode in JavaScript?

开发者 https://www.devze.com 2023-03-08 16:40 出处:网络
I\'m trying to create the equivalent of PHP\'s unpack. I\'ve noticed the project PHPJS doesn\'t have it. I need it for the implementation of base32_encode and base32_decode (using Crockford\'s alphabe

I'm trying to create the equivalent of PHP's unpack. I've noticed the project PHPJS doesn't have it. I need it for the implementation of base32_encode and base32_decode (using Crockford's alphabet '0123456789ABCDEFGH开发者_开发百科JKMNPQRSTVWXYZ').

I couldn't find it anywhere and judging from it's counterpart, PHPJS's pack function I doubt my version will be complete and bug free any time soon.


base32tohex = (function() {
    var dec2hex = function(s) {
        return (s < 15.5 ? "0" : "") + Math.round(s).toString(16)
    }
      , hex2dec = function(s) {
        return parseInt(s, 16)
    }
      , base32tohex = function(base32) {
        for (var base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", bits = "", hex = "", i = 0; i < base32.length; i++) {
            var val = base32chars.indexOf(base32.charAt(i).toUpperCase());
            bits += leftpad(val.toString(2), 5, "0")
        }
        for (i = 0; i + 4 <= bits.length; i += 4) {
            var chunk = bits.substr(i, 4);
            hex += parseInt(chunk, 2).toString(16)
        }
        return hex
    }
      , leftpad = function(str, len, pad) {
        return len + 1 >= str.length && (str = new Array(len + 1 - str.length).join(pad) + str),
        str
    };
    return base32tohex;
}
)()
0

精彩评论

暂无评论...
验证码 换一张
取 消