0

I need a function that takes the ASCII value of a JavaScript character (or whatever type of variable compose a JavaScript string) and returns a string of its bit representation. The ??? in the following code needs filled in.

function bitstring(var thisUnsigned)
{
    var retStr = "";
    for (var i = 0; i < ???; i++)
    {
        retStr += thisUnsigned & 1 ? "1" : "0";
        thisUnsigned >>= 1;
    }
    return retStr;
}

I've seen here How many bytes in a JavaScript string? that each character is 16 bits, but then again I know that an ASCII chart only has 127 characters in it.

Go easy on me. I'm on a JavaScript n00b. ;)

2

1 Answer 1

1
function bitstring( thisUnsigned ) {
    var bits = thisUnsigned.toString(2);
    return new Array(16-bits.length+1).join('0') + bits;
}

Examples:

bitstring('A'.charCodeAt(0)) // "0000000001000001" (65 in binary)
bitstring('☥'.charCodeAt(0)) // "0010011000100101" (9765 in binary)

What is the size of a character in a JavaScript string?

The above example shows that charCodeAt(0) returns 9765, which clearly requires more than a single byte to hold.

Sign up to request clarification or add additional context in comments.

Comments

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.