Java中位运算相关测试
layout: post title: “Java中位运算相关测试” description: “” category: [“Coding”] —
对应的代码注释如下
package com.dellyqiao;
import java.util.Arrays;
public class TestBinary {
public static void main(String[] args) {
System.out.println(51&5);
System.out.println(51|5);
System.out.println(51^5); //按位取值对比,不同为1,相同为0,可用来翻转某几位(1),用0保留原值
//变量交换值 (a^a为0,b^b为0。而数字^0为原数字。所以
//a^b为中间值,新b=中间值^b,新a=中间值^a)
int a = 51;
int b = 5;
a=a^b;
b=a^b;
a=a^b;
System.out.println(a + " " + b);
System.out.println(~0 + " " + ~1); //取反,每一位取反
System.out.println(2<<1); //左移。二进制位全部左移,左边二进制位丢弃,右边补0
//若舍弃的高位不包含1,则每左移一位,相当于乘以2
System.out.println(-14<<2);
System.out.println(4>>2); //右移。正数左补0,负数左补1,右边丢弃。
//每右移一位,相当于该数除以2。
System.out.println(-14>>2);
System.out.println(-14>>>2);//无符号右移。左补0,右丢弃
System.out.println(Integer.toBinaryString(112)); //转二进制
System.out.println(Integer.toHexString(112)); //转16进制
System.out.println(Integer.toOctalString(112)); //转8进制
System.out.println(Integer.parseInt("111001", 2)); //二进制转10进制
System.out.println(Integer.parseInt("27", 8)); //八进制转十进制
System.out.println(Integer.parseInt("1A", 16)); //16进制转十进制
//int转为byte[]
int id = 8143;
byte[] arr = new byte[4];
arr[0] = (byte)((int)(id >> 0*8) & 0xff);
arr[1] = (byte)((int)(id >> 1*8) & 0xff);
arr[2] = (byte)((int)(id >> 2*8) & 0xff);
arr[3] = (byte)((int)(id >> 3*8) & 0xff);
System.out.println(arr[0] +"," + arr[1] + "," + arr[2] + "," + arr[3]);
//byte[]转为int
int rs0 = (int)((arr[0] & 0xff) << 0*8);
int rs1 = (int)((arr[1] & 0xff) << 1*8);
int rs2 = (int)((arr[2] & 0xff) << 2*8);
int rs3 = (int)((arr[3] & 0xff) << 3*8);
System.out.println(rs0 + rs1 + rs2 + rs3);
//字符串与字节
String describe = "你好世界";
byte[] barr = describe.getBytes();
System.out.println(Arrays.toString(barr));
String des = new String(barr);
System.out.println(des);
}
}