Home > Web Front-end > JS Tutorial > How to convert string to binary in javascript

How to convert string to binary in javascript

青灯夜游
Release: 2022-01-26 16:17:46
Original
11014 people have browsed it

Conversion method: 1. Use the split() method to convert the string into a character array; 2. Traverse the character array and use the charCodeAt() and toString() methods to convert each character element into a binary value; 3. , use the join() method to splice the array elements and convert them into complete binary values.

How to convert string to binary in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Javascript converts a string to binary

  • Converts a string to a character array

  • Traverse the character array and use charCodeAt() to convert each character element to ascii code

  • Use toString(2) to convert the ascii code element to binary

  • Use join() to splice array elements and convert them into binary strings.

Implementation code:

function strToBinary(str){
    var result = [];
    var list = str.split("");
    for(var i=0;i<list.length;i++){
        if(i != 0){
            result.push(" ");
        }
        var item = list[i];
        var binaryStr = item.charCodeAt().toString(2);
        result.push(binaryStr);
    }   
    return result.join("");
}
 
console.log(strToBinary("我们")); //110001000010001 100111011101100
Copy after login

How to convert string to binary in javascript

[Related recommendations: javascript learning tutorial]

The above is the detailed content of How to convert string to binary in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template