^异或运算符
其运算法则是对运算符两侧数的每一个二进制位,同值取0,异值取1。
异或运算最常见于多项式除法,不过它最重要的性质还是自反性:A ^ B ^ B = A,
与运算
用1与叫做保留,用0与叫做消除。
注:
当0~1之间的浮点实数用二进制来表示使 采用 乘2挪整的方法(见例题三)
当 十进制整数转二进制 是 除2取余法
例如:把15化为二进制的数
15÷2=7余1
7÷2=3余1
3÷2=1余1
1÷2=0余1
二进制表示为1111
例题1
-----------找出唯一成对的数-----------
import java.util.Random; public class BitOperation_Test001_XOR { public static void main(String[] args) { /* * 1----0001 * 2----0010 * 1^2--0011 * 3----0011 * 1^2^3--0000 * 4----0100 * 1^2^3^4--0100 * 1^2^3^4^4--0000 * 1^2^3^4^4 ^ 1^2^3^4=0100=4 * * 1*2*2+0*2+0=4 */ int n=11; int [] arr=new int[n]; for (int i = 0; i < arr.length-1; i++) { arr[i]=i+1; } Random random=new Random(); /* random.nextInt(n)范围是[0,n) */ arr[n-1]=random.nextInt(n-1)+1; for (int i: arr) { System.out.print(i+"\t"); } int temp1=0; /* 除了那个随机数外的数进行异或 */ for (int i = 0; i < n-1; i++) { temp1 =temp1^arr[i]; } int temp2=0; /* 所有数进行异或 */ for (int i = 0; i < n; i++) { temp2 =temp2^arr[i]; } int result=temp1^temp2; System.out.println("重复的数字是:"+result); } }
例题二
将整数的奇偶位互换
import java.util.Scanner; public class BitOperation_Test002_XOR { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); int num=scanner.nextInt(); System.out.println("原二进制表示为:"+Integer.toString(num,2)); /*二进制 每4位都可以用1个十六进制来表示*/ /* 1010 返回偶数位的数*/ int a=num&0xaaaaaaaa; /* 0101 返回奇数位的数*/ int b=num&0x55555555; /* 将偶数位右移1位,奇数为左移一位*/ int temp=a>>1^b<<1; System.out.println("结果为"+temp+ "二进制表示为"+Integer.toString(temp,2)); } }
例题三
0~1之间的浮点实数用二进制来表示
public class garbage { public static void main(String[] args) { double num=0.625; StringBuilder stringBuilder=new StringBuilder("0."); while (num!=0){ double num1=num*2; if (num1>=1){ stringBuilder.append("1"); num=num1-1; }else { stringBuilder.append("0"); num=num1; } } /*十六进制32位 0.两位 */ if (stringBuilder.length()>34){ System.out.println("error"); } System.out.println(stringBuilder.toString()); } }