JavaScript中(|)按位OR与(^)按位XOR之间的区别 [英] Difference between (|) Bitwise OR vs (^) Bitwise XOR in JavaScript

查看:66
本文介绍了JavaScript中(|)按位OR与(^)按位XOR之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在 JavaScript 中使用 | OR与 ^ XOR的使用感到非常困惑,如下面的简单示例所示;

I'm really getting confused on the use of the | OR vs ^ XOR in JavaScript, illustrated in the simple example below;

(function sayHi(n){
if(n < 1)   //base case
    return;
console.log("Hi!!" | "Hello!!") ;
sayHi(n - 1);   //recurse
})(5);


(function sayHi(n){
if(n < 1)   //base case
    return;
console.log("Hi!!" ^ "Hello!!") ;
sayHi(n - 1);   //recurse
})(5);


(function sayHi(n){
if(n < 1)   //base case
    return;
console.log(2 | 6) ;
sayHi(n - 1);   //recurse
})(5);


(function sayHi(n){
if(n < 1)   //base case
    return;
console.log(2 ^ 6) ;
sayHi(n - 1);   //recurse
})(5);

我对何时,如何,为什么,在哪里应该使用 | vs ^ 感到困惑.

I'm confused about when, how, why, where I should appropriate use | vs ^.

有人可以帮助我理解 OR XOR 操作之间的主要区别吗?

Can someone please help me make sense the major difference between OR and XOR operations?

我正在从 MDN中阅读JavaScript文档.网络文档,以更好地理解按位运算的概念,但我仍在努力理解它们的显着差异.

I was reading the documentation for JavaScript from MDN web Docs to better understand the concept of bitwise operations, but I am struggling to understand their significant difference.

我只想确保此后继续正确使用这些操作.

I just want to make sure I continue to use these operations correctly henceforth.

非常感谢预期的帮助!

推荐答案

OR和XOR是不同的运算符:

OR and XOR are different operators:

  • OR:

  • OR:

0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1

  • 异或

  • XOR

    0 ^ 0 = 0
    0 ^ 1 = 1
    1 ^ 0 = 1
    1 ^ 1 = 0
    

  • 如果您有两个位并将它们与OR组合,则如果这些位之一或两者都为1,则结果将为1.如果将它们与XOR(异或)相结合,则仅当其中之一为1时,结果将为1.位是1(如果不是两个,则不是).

    If you have two bits and combine these with OR, the result will be 1, if one of these bits or both are 1. If you combine them with XOR (Exclusive OR) then it will be 1 if only one of these bits are 1 (not if both).

    这篇关于JavaScript中(|)按位OR与(^)按位XOR之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆