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