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

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I want to encode query string to make it look like id hash. Like rewritten link.
Encoding != hash, so I hope you're not using this for security purposes!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.