Q:

How to map binary data to characters in javascript?

For the API I'm working on, I have to map bytes to characters by these rules:

Bytes 0x20 to 0x24 inclusive are mapped to the corresponding characters U+0020 to U+0024 inclusive.
Bytes 0x26 to 0x7E inclusive are mapped to the corresponding characters U+0026 to U+007E inclusive. 
Other bytes are mapped to the three character sequence consisting of a percent character followed by two uppercase hex characters, e.g. byte 0 maps to “%00” and byte 0xAB maps to “%AB”.

That's for encoding, I have to make function for decoding also.
Is this maybe some existing encoding? I googled it, but couldn't find anything.
I know U+ is for Unicode. 
Can I just map it like:
if(bytesArray[i] == 0x21)
{
    bytesArray[i] = U+0021;
}

?

A:

Since you are translating values in a string, you can use String.replace. The only thing that actually needs replacing is the %XX notation; other characters can stay unchanged.
In this case you can use the user defined function of the replace command:
decodedArray = byteArray.replace (/%([0-9A-F][0-9A-F])/g,
    function (match, p1)
    {
        return String.fromCharCode(parseInt(p1, 16));
    } );

This is a safe operation because per the specification, a literal % character may not appear in the encoded string (in case you're wondering: that is the code 0x25 that gets singled out in the otherwise printable plain ASCII range). Even if a stray % appears in the string, it will only be replaced if actually followed by two valid capitalized hex bytes.
Encoding is similarly straightforward:
encodedArray = originalString.replace (/[^ -$&-~]/g,
    function (match)
    {
        if (match.charCodeAt(0) < 16)
           return '%0'+match.charCodeAt(0).toString(16).toUpperCase();
        return '%'+match.charCodeAt(0).toString(16).toUpperCase();
    } );

Note the 'match' regex is the exact ASCII representation of your to-be-translated code list; it is negated because you want to find all characters 
outside that range.
This works better than a mapping, because that would require you to manually loop over each character and inspect it to decide whether or not it needs translating. This would work reasonably well for encoding (you'd need a list of all codes, with either a one- or 3-byte string to which it encodes) but for decoding you would need to look 2 bytes ahead, test if they are valid (!), and skip over them if so. Compared to that, the replace solution ought to be much faster.

