Java 中的 ^ 运算符有什么作用?

发布于 2024-08-16 18:42:49 字数 241 浏览 5 评论 0原文

Java 中 ^(插入符号)运算符有什么功能?

当我尝试这个时:

int a = 5^n;

...它给了我:

对于 n = 5,返回 0
对于 n = 4,返回 1
对于 n = 6,返回 3

...所以我猜它不执行求幂。但那又是什么呢?

What function does the ^ (caret) operator serve in Java?

When I try this:

int a = 5^n;

...it gives me:

for n = 5, returns 0
for n = 4, returns 1
for n = 6, returns 3

...so I guess it doesn't perform exponentiation. But what is it then?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

℉服软 2024-08-23 18:42:49

Java ^ 中的 ^ 运算符

是异或(“xor”)运算符。

让我们以 5^6 为例:

(decimal)    (binary)
     5     =  101
     6     =  110
------------------ xor
     3     =  011

这是按位的真值表 (JLS 15.22.1)和逻辑(JLS 15.22.2) xor:

^ | 0 1      ^ | F T
--+-----     --+-----
0 | 0 1      F | F T
1 | 1 0      T | T F

更简单地说,你也可以将 xor 视为“这个或 那个,但不是两者!”。

另请参阅


Java 中的求幂

至于整数求幂,不幸的是 Java 没有有这样一个运营商。您可以使用 < code>double Math.pow(double, double)(如有必要,将结果转换为 int)。

您还可以使用传统的位移位技巧来计算 2 的某些幂。也就是说,对于 k=0..63(1L << k) 是 2 的 k 次方。

另请参阅


合并注释:此答案是从另一个问题合并而来的,该问题的目的是使用求幂将字符串 "8675309" 转换为 < code>int 而不使用 Integer.parseInt 作为编程练习(^ 表示从现在开始求幂)。 OP的目的是计算8*10^6 + 6*10^5 + 7*10^4 + 5*10^3 + 3*10^2 + 0*10^1 + 9*10^0 = 8675309 ;该答案的下一部分指出,此任务不需要求幂。


霍纳的方案

为了满足您的特定需求,您实际上不需要计算 10 的各种幂。您可以使用所谓的 霍纳方案,不仅简单而且高效。

由于您将此作为个人练习,因此我不会提供 Java 代码,但主要思想如下:

8675309 = 8*10^6 + 6*10^5 + 7*10^4 + 5*10^3 + 3*10^2 + 0*10^1 + 9*10^0
        = (((((8*10 + 6)*10 + 7)*10 + 5)*10 + 3)*10 + 0)*10 + 9

乍一看可能看起来很复杂,但实际上并不复杂。您基本上从左到右读取数字,然后将到目前为止的结果乘以 10,然后再添加下一个数字。

以表格形式:

step   result  digit  result*10+digit
   1   init=0      8                8
   2        8      6               86
   3       86      7              867
   4      867      5             8675
   5     8675      3            86753
   6    86753      0           867530
   7   867530      9          8675309=final

The ^ operator in Java

^ in Java is the exclusive-or ("xor") operator.

Let's take 5^6 as example:

(decimal)    (binary)
     5     =  101
     6     =  110
------------------ xor
     3     =  011

This the truth table for bitwise (JLS 15.22.1) and logical (JLS 15.22.2) xor:

^ | 0 1      ^ | F T
--+-----     --+-----
0 | 0 1      F | F T
1 | 1 0      T | T F

More simply, you can also think of xor as "this or that, but not both!".

See also


Exponentiation in Java

As for integer exponentiation, unfortunately Java does not have such an operator. You can use double Math.pow(double, double) (casting the result to int if necessary).

You can also use the traditional bit-shifting trick to compute some powers of two. That is, (1L << k) is two to the k-th power for k=0..63.

See also


Merge note: this answer was merged from another question where the intention was to use exponentiation to convert a string "8675309" to int without using Integer.parseInt as a programming exercise (^ denotes exponentiation from now on). The OP's intention was to compute 8*10^6 + 6*10^5 + 7*10^4 + 5*10^3 + 3*10^2 + 0*10^1 + 9*10^0 = 8675309; the next part of this answer addresses that exponentiation is not necessary for this task.

Horner's scheme

Addressing your specific need, you actually don't need to compute various powers of 10. You can use what is called the Horner's scheme, which is not only simple but also efficient.

Since you're doing this as a personal exercise, I won't give the Java code, but here's the main idea:

8675309 = 8*10^6 + 6*10^5 + 7*10^4 + 5*10^3 + 3*10^2 + 0*10^1 + 9*10^0
        = (((((8*10 + 6)*10 + 7)*10 + 5)*10 + 3)*10 + 0)*10 + 9

It may look complicated at first, but it really isn't. You basically read the digits left to right, and you multiply your result so far by 10 before adding the next digit.

In table form:

step   result  digit  result*10+digit
   1   init=0      8                8
   2        8      6               86
   3       86      7              867
   4      867      5             8675
   5     8675      3            86753
   6    86753      0           867530
   7   867530      9          8675309=final
贩梦商人 2024-08-23 18:42:49

正如许多人已经指出的那样,它是 XOR 运算符。许多人也已经指出,如果你想要求幂,那么你需要使用 Math.pow

但我认为注意到 ^ 只是统称为按位运算符的一系列运算符之一也很有用:

Operator    Name         Example     Result  Description
a & b       and          3 & 5       1       1 if both bits are 1.
a | b       or           3 | 5       7       1 if either bit is 1.
a ^ b       xor          3 ^ 5       6       1 if both bits are different.
~a          not          ~3          -4      Inverts the bits.
n << p      left shift   3 << 2      12      Shifts the bits of n left p positions. Zero bits are shifted into the low-order positions.
n >> p      right shift  5 >> 2      1       Shifts the bits of n right p positions. If n is a 2's complement signed number, the sign bit is shifted into the high-order positions.
n >>> p     right shift  -4 >>> 28   15      Shifts the bits of n right p positions. Zeros are shifted into the high-order positions.

来自 此处

当您需要读取和写入整数(其中各个位应解释为标志)时,或者当整数中的特定范围的位具有特殊含义并且您只想提取这些位时,这些运算符会派上用场。您可以进行大量的日常编程,而无需使用这些运算符,但如果您必须处理位级别的数据,那么充分了解这些运算符是非常宝贵的。

As many people have already pointed out, it's the XOR operator. Many people have also already pointed out that if you want exponentiation then you need to use Math.pow.

But I think it's also useful to note that ^ is just one of a family of operators that are collectively known as bitwise operators:

Operator    Name         Example     Result  Description
a & b       and          3 & 5       1       1 if both bits are 1.
a | b       or           3 | 5       7       1 if either bit is 1.
a ^ b       xor          3 ^ 5       6       1 if both bits are different.
~a          not          ~3          -4      Inverts the bits.
n << p      left shift   3 << 2      12      Shifts the bits of n left p positions. Zero bits are shifted into the low-order positions.
n >> p      right shift  5 >> 2      1       Shifts the bits of n right p positions. If n is a 2's complement signed number, the sign bit is shifted into the high-order positions.
n >>> p     right shift  -4 >>> 28   15      Shifts the bits of n right p positions. Zeros are shifted into the high-order positions.

From here.

These operators can come in handy when you need to read and write to integers where the individual bits should be interpreted as flags, or when a specific range of bits in an integer have a special meaning and you want to extract only those. You can do a lot of every day programming without ever needing to use these operators, but if you ever have to work with data at the bit level, a good knowledge of these operators is invaluable.

你的他你的她 2024-08-23 18:42:49

它是按位异或,Java 没有幂运算符,您必须使用 Math.pow() 代替。

It's bitwise XOR, Java does not have an exponentiation operator, you would have to use Math.pow() instead.

可遇━不可求 2024-08-23 18:42:49

异或运算符规则 =>

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

4、5和6的二进制表示:

4 = 1 0 0 
5 = 1 0 1
6 = 1 1 0

现在,对5和4进行异或运算:

     5 ^ 4 => 1  0  1   (5)
              1  0  0   (4)
            ----------
              0  0  1   => 1

同样,

5 ^ 5 => 1   0   1    (5)
         1   0   1    (5)
       ------------
         0   0   0   => (0)


5 ^ 6 => 1   0   1  (5)
         1   1   0  (6)
        -----------
         0   1   1  => 3

XOR operator rule =>

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

Binary representation of 4, 5 and 6 :

4 = 1 0 0 
5 = 1 0 1
6 = 1 1 0

now, perform XOR operation on 5 and 4:

     5 ^ 4 => 1  0  1   (5)
              1  0  0   (4)
            ----------
              0  0  1   => 1

Similarly,

5 ^ 5 => 1   0   1    (5)
         1   0   1    (5)
       ------------
         0   0   0   => (0)


5 ^ 6 => 1   0   1  (5)
         1   1   0  (6)
        -----------
         0   1   1  => 3
涫野音 2024-08-23 18:42:49

它是 XOR 位运算符。

It is the XOR bitwise operator.

余生共白头 2024-08-23 18:42:49

很多人已经解释过它是什么以及如何使用它,但除了显而易见的事情之外,您还可以使用此运算符执行许多编程技巧,例如对

  • 布尔数组中的所有元素进行异或会告诉您该数组是否具有奇数个真实元素
  • 如果您有一个数组,其中所有数字重复偶数次(除了重复奇数次的数字除外),您可以通过对所有元素进行异或来找到该数组。
  • 不使用临时变量交换值
  • 查找 1 到 n 范围内的缺失数字 对
  • 通过网络发送的数据进行基本验证。

使用位运算符可以完成很多这样的技巧,这是一个值得探索的有趣主题。

Lot many people have already explained about what it is and how it can be used but apart from the obvious you can use this operator to do a lot of programming tricks like

  • XORing of all the elements in a boolean array would tell you if the array has odd number of true elements
  • If you have an array with all numbers repeating even number of times except one which repeats odd number of times you can find that by XORing all elements.
  • Swapping values without using temporary variable
  • Finding missing number in the range 1 to n
  • Basic validation of data sent over the network.

Lot many such tricks can be done using bit wise operators, interesting topic to explore.

笑看君怀她人 2024-08-23 18:42:49

XOR 运算符规则

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

按位运算符作用于位并执行逐位运算。假设a = 60且b = 13;现在以二进制格式,它们将如下 -

a = 0011 1100

b = 0000 1101



a^b ==> 0011 1100  (a)
        0000 1101  (b)
        -------------  XOR
        0011 0001  => 49

(a ^ b) will give 49 which is 0011 0001

XOR operator rule

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

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows −

a = 0011 1100

b = 0000 1101



a^b ==> 0011 1100  (a)
        0000 1101  (b)
        -------------  XOR
        0011 0001  => 49

(a ^ b) will give 49 which is 0011 0001
慵挽 2024-08-23 18:42:49

正如其他人所说,它是按位异或。如果要将数字提高到给定幂,请使用 Math.pow(a , b),其中 a 是数字,b 是的力量。

As others have said, it's bitwise XOR. If you want to raise a number to a given power, use Math.pow(a , b), where a is a number and b is the power.

筱果果 2024-08-23 18:42:49

AraK 的链接指向异或的定义,它解释了该函数如何对两个布尔值起作用。

缺少的信息是这如何应用于两个整数(或整数类型值)。按位异或应用于两个数字中相应的二进制数字对,并将结果重新组合成整数结果。

使用您的示例:

  • 5 的二进制表示形式是 0101。4
  • 的二进制表示形式是 0100。

定义按位异或的一种简单方法是,结果在两个输入数字不同的每个地方都有 1。

4 和 5 唯一的区别是最后一位;所以

0101 ^ 0100 = 0001 (5 ^ 4 = 1) 。

AraK's link points to the definition of exclusive-or, which explains how this function works for two boolean values.

The missing piece of information is how this applies to two integers (or integer-type values). Bitwise exclusive-or is applied to pairs of corresponding binary digits in two numbers, and the results are re-assembled into an integer result.

To use your example:

  • The binary representation of 5 is 0101.
  • The binary representation of 4 is 0100.

A simple way to define bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.

With 4 and 5, the only difference is in the last place; so

0101 ^ 0100 = 0001 (5 ^ 4 = 1) .

转身泪倾城 2024-08-23 18:42:49

这是java中的按位异或运算符,当数字以二进制形式写入时,不同位值(即1 ^ 0 = 1)结果为1,相同位值(即0 ^ 0 = 0)结果为0。

ex :-

使用您的示例:

5 的二进制表示形式是 0101。
4 的二进制表示形式是 0100。

定义按位异或的一种简单方法是,结果在两个输入数字不同的每个地方都有 1。

0101^0100=0001(5^4=1)。

It is the Bitwise xor operator in java which results 1 for different value of bit (ie 1 ^ 0 = 1) and 0 for same value of bit (ie 0 ^ 0 = 0) when a number is written in binary form.

ex :-

To use your example:

The binary representation of 5 is 0101.
The binary representation of 4 is 0100.

A simple way to define Bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.

0101 ^ 0100 = 0001 (5 ^ 4 = 1) .

忱杏 2024-08-23 18:42:49

正如其他答案已经指出的那样,它是 “异或”(XOR) 运算符 。有关 Java 中位运算符的更多信息,请参阅:http:// /java.sun.com/docs/books/tutorial/java/nutsandbolts/op3.html

As already stated by the other answer(s), it's the "exclusive or" (XOR) operator. For more information on bit-operators in Java, see: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op3.html

看轻我的陪伴 2024-08-23 18:42:49

那是因为您正在使用异或运算符。

在 Java 或任何其他语言中,^ 是按位异或,
所以当然,

10 ^ 1 = 11。
有关按位运算符的更多信息

有趣的是,Java 和 C# 没有幂运算符。

That is because you are using the xor operator.

In java, or just about any other language, ^ is bitwise xor,
so of course,

10 ^ 1 = 11.
more info about bitwise operators

It's interesting how Java and C# don't have a power operator.

无语# 2024-08-23 18:42:49

它是java中的按位异或运算符,对于不同的值(即1 ^ 0 = 1)结果为1,对于相同的值结果为0(即0 ^ 0 = 0)。

It is the bitwise xor operator in java which results 1 for different value (ie 1 ^ 0 = 1) and 0 for same value (ie 0 ^ 0 = 0).

烟雨凡馨 2024-08-23 18:42:49

^ 是二进制(如以 2 为基数)异或,而不是求幂(不能用作 Java 运算符)。有关求幂,请参阅 java.lang.Math.pow()。

^ is binary (as in base-2) xor, not exponentiation (which is not available as a Java operator). For exponentiation, see java.lang.Math.pow().

屋顶上的小猫咪 2024-08-23 18:42:49

它是异或运算符。它用于对数字进行位运算。它的行为是,当您对相同的位进行异或运算时,例如 0 XOR 0 / 1 XOR 1,结果为 0。但如果任何位不同,则结果为 1。
因此,当您执行 5^3 时,您可以查看这些数字 5、6 的二进制形式,因此表达式变为 (101) XOR (110),得到结果 (011),其十进制表示形式为 3。

It is XOR operator. It is use to do bit operations on numbers. It has the behavior such that when you do a xor operation on same bits say 0 XOR 0 / 1 XOR 1 the result is 0. But if any of the bits is different then result is 1.
So when you did 5^3 then you can look at these numbers 5, 6 in their binary forms and thus the expression becomes (101) XOR (110) which gives the result (011) whose decimal representation is 3.

霊感 2024-08-23 18:42:49

作为其他答案的补充,值得一提的是,插入符号运算符也可以与布尔操作数一起使用,并且它返回 true (当且仅当)操作数不同:

    System.out.println(true ^ true); // false
    System.out.println(true ^ false); // true
    System.out.println(false ^ false); // false
    System.out.println(false ^ true); // true

As an addition to the other answers, it's worth mentioning that the caret operator can also be used with boolean operands, and it returns true (if and only if) the operands are different:

    System.out.println(true ^ true); // false
    System.out.println(true ^ false); // true
    System.out.println(false ^ false); // false
    System.out.println(false ^ true); // true
零崎曲识 2024-08-23 18:42:49

查看 x^y 的 XOR 运算符的另一种方式是 x y 不同,但对于每一位。

由于布尔值可以表示为单个位,因此上面的内容对于布尔值也是透明的。

Another way of looking at the XOR operator for x^y, is x is not the same as y, but for each bit.

Since boolean values can be represented as a single bit, the above is also transparent to boolean values.

爱给你人给你 2024-08-23 18:42:49

在其他语言(例如 Python)中,您可以执行 10**2=100,尝试一下。

In other languages like Python you can do 10**2=100, try it.

梦中的蝴蝶 2024-08-23 18:42:49

^ =(按位异或)

说明

如果在一个操作数中设置了该位,但不是在两个操作数中都设置了该位,则二元异或运算符会复制该位。

例子

(A ^ B) 将给出 49,即 0011 0001

^ = (bitwise XOR)

Description

Binary XOR Operator copies the bit if it is set in one operand but not both.

example

(A ^ B) will give 49 which is 0011 0001

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文