2

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 '0123456789ABCDEFGHJKMNPQRSTVWXYZ').

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.

Brett Zamir
  • 13,309
  • 6
  • 48
  • 73
Valentin Brasso
  • 1,397
  • 6
  • 21
  • 41

4 Answers4

4
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;
}
)()
Zibri
  • 8,006
  • 3
  • 47
  • 40
  • To conform to [rfc4648](https://tools.ietf.org/html/rfc4648#section-6), the for loop calculating the hex representation should instead be `for (i = 0; i + 8 <= bits.length; i += 8)`. This is because it's illegal for base32 input to be a fractional number of bytes, so we must ignore any bits left over at the end of the decoded string. – LS97 Mar 22 '21 at 16:17
1

You could modify a JavaScript Base64 function to use the smaller alphabet.

Community
  • 1
  • 1
maerics
  • 143,080
  • 41
  • 260
  • 285
  • It is not trivial because the length of chunk is also changed. Encoded sequence consists of 8-octet chunks and not from 3-octet ones as it was in base64. – Sergey Sep 27 '21 at 21:57
1

What about this? It looks like it will get you half way there.

http://forthescience.org/blog/2010/11/30/base32-encoding-in-javascript/

Doug Chamberlain
  • 11,069
  • 9
  • 47
  • 91
0

it turns out someone had already done both encode and decode functions

https://github.com/agnoster/base32-js/blob/master/lib/base32.js

Valentin Brasso
  • 1,397
  • 6
  • 21
  • 41
  • 1
    Are there any packages that do not have the crypto package because it cannot be run in the browser. It has to have node – isethi Jan 05 '22 at 20:27