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. ;)

Community
  • 1
  • 1
user3407988
  • 121
  • 1
  • 3
  • 6
  • http://stackoverflow.com/questions/7859826/how-to-efficiently-read-bits-out-of-bytes – adeneo Mar 14 '14 at 21:46
  • See here. http://stackoverflow.com/questions/94037/convert-character-to-ascii-code-in-javascript And Here. http://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript – Preston S Mar 14 '14 at 21:47

1 Answers1

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.

Matt
  • 20,108
  • 1
  • 57
  • 70