1

Is there a way to encode regular javascript utf-8 string into decimal 0-9 ( or octal 0-7 if that's more convenient) (octal or base10) ?

I saw this thread for php, I want similar for javascript.

Encoding byte data into digits

Community
  • 1
  • 1
Ime Ime
  • 133
  • 5
  • 12

1 Answers1

4

Not sure why you want to do this exactly, but depending on your needs, it's easy enough. JavaScript's String.prototype.charCodeAt() returns the numeric Unicode value of the characters in a string, which can go up to 65,536 (assuming your are not using unicode codepoints > 0x10000; if you are, consult the String.prototype.charCodeAt documentation).

Chances are, you're using ASCII, meaning your numeric character codes will be, at most, 255, meaning you could get by with three digits. So first we'll need a function to pad zeros:

function zeroPad(n, w){
    while(n.toString().length<w) n = '0' + n;
    return n;
}

Then we can create a function to convert your string to a string of numbers:

function toNumbers(s){
    var nums = '';
    for(var i=0; i<s.length; i++) {
        nums += zeroPad(s.charCodeAt(i), 3);
    }
    return nums;
}

Then a function to decode:

function fromNumbers(nums){
    var s = '';
    for(var i=0; i<nums.length; i+=3){
        console.log(i + ': ' + nums.substring(i, i+3))
        s += String.fromCharCode(nums.substring(i, i+3));
    }
    return s;
}
Ethan Brown
  • 26,892
  • 4
  • 80
  • 92