jeudi 1 janvier 2015

Base conversion of a string in Javascript


I'm trying to succinctly convert the string "eamorr" to "2018e8c" in node.js


"eamorr" is in base32 and "2018e8c" is some sort of hex (I'm not sure).


Using code grabbed from http://ift.tt/1B9QZXU, here's how I'm currently doing it:



function base32tohex(base32) {
var base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
var bits = "";
var hex = "";

for (var i = 0; i < base32.length; i++) {
var val = base32chars.indexOf(base32.charAt(i).toUpperCase());
bits += leftpad(val.toString(2), 5, '0');
}

for (var i = 0; i+4 <= bits.length; i+=4) {
var chunk = bits.substr(i, 4);
hex = hex + parseInt(chunk, 2).toString(16) ;
}
return hex;
}
function leftpad(str, len, pad) {
if (len + 1 >= str.length) {
str = Array(len + 1 - str.length).join(pad) + str;
}
return str;
}
var key="eamorr"
console.log(base32tohex(key)); //prints the correct string (2018e8c)


This works fine for me. But surely there must be a more succinct way of doing this using just built-in functions?


Here's what I've tried:



var base32 = require('base32');
var buff = new Buffer(base32.decode("eamorr"),'utf8');
console.log(buff.toString('hex'));


This requires 'base32', and it prints out the wrong result "72c2a80c" ;(





Aucun commentaire:

Enregistrer un commentaire