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;
}
)()
精彩评论