How to convert text to binary code in JavaScript?

后端 未结 13 1821
囚心锁ツ
囚心锁ツ 2020-11-28 05:00

Text to Binary Code

I want JavaScript to translate text in a textarea into binary code.

For example, if a user types in "TEST

13条回答
  •  孤独总比滥情好
    2020-11-28 05:21

    The other answers will work for most cases. But it's worth noting that charCodeAt() and related don't work with UTF-8 strings (that is, they throw errors if there are any characters outside the standard ASCII range). Here's a workaround.

    // UTF-8 to binary
    var utf8ToBin = function( s ){
        s = unescape( encodeURIComponent( s ) );
        var chr, i = 0, l = s.length, out = '';
        for( ; i < l; i ++ ){
            chr = s.charCodeAt( i ).toString( 2 );
            while( chr.length % 8 != 0 ){ chr = '0' + chr; }
            out += chr;
        }
        return out;
    };
    
    // Binary to UTF-8
    var binToUtf8 = function( s ){
        var i = 0, l = s.length, chr, out = '';
        for( ; i < l; i += 8 ){
            chr = parseInt( s.substr( i, 8 ), 2 ).toString( 16 );
            out += '%' + ( ( chr.length % 2 == 0 ) ? chr : '0' + chr );
        }
        return decodeURIComponent( out );
    };
    

    The escape/unescape() functions are deprecated. If you need polyfills for them, you can check out the more comprehensive UTF-8 encoding example found here: http://jsfiddle.net/47zwb41o

提交回复
热议问题