Search code examples
javascriptbitwise-operators

How to use the PHP bitwise AND operator with Javascript


I am trying to do what PHP does with the & AND operator but in javascript. An example would be the following:

// PHP
$a = '100110100011111000100110';
$b = '111111111111111111111110';

echo $a & $b //100110100011111000100110

Well, it is the result that I must achieve in javascript ... trying it from the beginning would be ..

// JS
const a = 100110100011111000100110;
const b = 111111111111111111111110;

console.log(a & b) //536870912

Honestly, I know very little about binary, I have tried some functions using bitwise XOR and reviewed the topic right here in StackOverflow but the truth is confused.


Solution

  • Well thanks to the comments of those who responded, and looking and entering the topic, I reviewed the documentation of both languages and then what I did was divide the strings, and do the and - & to each pair of their position and the result it was similar to php.

    here as I did.

    const a = '100110100011111000100110';
    const b = '111111111111111111111110';
    
    function andBin (one, two) {
      const _a = one.split('')
      const _b = two.split('')
      let result = ''
    
      _a.map((e, i) => {
        result += Number(e) & Number(_b[i])
      })
    
      return result
    
    }
    
    andBin(a, b) // 100110100011111000100110
    

    ready. resolved, thank you all very much.