Bitwise operations of Javascript strings in binary form

Source: Internet
Author: User

A string is similar to "1001001" and requires bitwise operations in binary form. However, in reality, Javascript will convert it to binary in decimal form, and then return the decimal result, this is not the expected result.

I want to directly treat this string as binary. Unfortunately, Javascript does not provide a method to treat the string as binary. It only provides the toString (2) method to convert the decimal number into binary ), therefore, we need to find a method that can directly perform bitwise operations on strings in the form of binary numbers.

Idea: traverse every character in each string

[Bitwise AND &: if the character is 1, 1 is added to the corresponding bitwise value of the new array, and 1 or 0 is returned by judging whether the value is equal to the number of strings.]

[Bitwise AND |: if the character is 1, the value of 1 is given to the corresponding bit of the new array. Otherwise, the value of 0 is returned.]

The following functions are calculated by bit or |

/** Convert String "100010" as Binary "100010" */function binaryOr (arr) {var len1 = arr. length, len2 = 0; var arrItem = ""; var resultArr = new Array (len1); for (var I = 0; I <len1; I ++) {// traverse every string in the array. arrItem = arr [I]; len2 = arrItem. length; for (var j = 0; j <len2; j ++) {// if (arrItem [j] = 1) {resultArr [j] = 1 ;}else {resultArr [j] = 0 ;}} console. log (resultArr);} var curArr = ["001010", "001100"]; binaryOr (curArr );


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.