Why 10^1 is 11?

六月ゝ 毕业季﹏ 提交于 2019-11-27 06:42:29

问题


I am currently learning C++. I was trying to compute power of an integer using the expression:

val=10^1;

Instead of expected answer 10, the result was 11. I have fixed the problem by using pow function of math.h library but I am wondering why this statement is giving me the wrong result.


回答1:


Because ^ is the exclusive or operator and not the exponentiation operator. Basically, because the last bit of 10 in binary is 0, by applying exclusive or of 1 the last bit gets converted to 1 because it is different than 0.




回答2:


No! Do you think that is the power? Don't forgot this (In C++ and some of the programming languages):

Be sure to read this:

  • Operators (cplusplus)

  • Bitwise operation (wikipedia)


A bitwise XOR takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. In this we perform the comparison of two bits, being 1 if the two bits are different, and 0 if they are the same. For example:

    0101 (decimal 5)
XOR 0011 (decimal 3)
  = 0110 (decimal 6)

The bitwise XOR may be used to invert selected bits in a register (also called toggle or flip). Any bit may be toggled by XORing it with 1. For example, given the bit pattern 0010 (decimal 2) the second and fourth bits may be toggled by a bitwise XOR with a bit pattern containing 1 in the second and fourth positions:

    0010 (decimal 2)
XOR 1010 (decimal 10)
  = 1000 (decimal 8)

This technique may be used to manipulate bit patterns representing sets of Boolean states.

Source: Wikipedia




回答3:


That's the bitwise exclusive-or operator, not power. In binary:

10 = 1010
 1 = 0001
val= 1011 = 11 in decimal



回答4:


In C and C++, 10^1 is 10 XOR 1, not 10 to the power of 1.




回答5:


Because in C++ there is no power operator: ^ is a XOR.

1010 is 10102 in binary; 110 is 00012. XORing them together gives 10112, which is 1110.

If you would like to obtain 10n, use the pow function from <cmath> header:

val=pow(10, 1);



回答6:


^ is the binary XOR operator in C++:

10 ^ 1 = 

   00001010
^  00000001
=  --------
   00001011 = 11


来源:https://stackoverflow.com/questions/19730348/why-101-is-11

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!