一、二进制基础
1.二进制位运算
(1) << : 左移 --》3 << 2 = 12
(2) >> : 右移 3 >> 1 : 3/2=1
(3) >>> :无符号右移动 3 >>> 1 : 3/2=1
异或本身等于0 ,与0异或保留原值-----》交换:A= A^B; B=A^B; A = A^B;
//1.利用加减法实现两个变量的交换
int A = 10 ;
int B = 11;
A=A+B;
B=A-B;
A=A-B;
System.out.println("A="+A+" B="+B);
//异或本身等于0 ,与0异或保留原值
A=A^B;
B=A^B;
A=A^B;
System.out.println("A="+A+" B="+B);
二、java 进制
public class Convert {
// int转化为byte[]
public static byte[] int2Bytes(int id) {
byte[] arr = new byte[4];
int i = 0;
int len = arr.length;
for (; i < len; i++) {//取低四位,每次取1bit(8字節)
arr[i] = (byte) ((int) ((id >> i* 8) & 0xff));
}
return arr;
}
// long转化为byte[]
public static byte[] Long2Bytes(long id) {
byte[] arr = new byte[8];
int i = 0;
int len = arr.length;
for (; i < len; i++) {//取低四位,每次取1bit(8字節)
arr[i] = (byte) ((int) ((id >> i* 8) & 0xff));
}
return arr;
}
//bytes轉化為int
public static int bytes2Int(byte[]arr)
{
int i= 0 ;
int tmp = 0;
int sum = 0;
int len = arr.length;
for ( ; i < len; i++ )
{
tmp=(int)((arr[i]&0xff)<<i*8);
sum+=tmp;
}
return sum;
}
//bytes轉化為int
public static int bytes2Long(byte[]arr)
{
int i= 0 ;
int tmp = 0;
int sum = 0;
int len = arr.length;
for ( ; i < len; i++ )
{
tmp=(int)((arr[i]&0xff)<<i*8);
sum+=tmp;
}
return sum;
}
public static void main(String[] args) {
int id = 8143;
byte arr[]=int2Bytes(id);
for (byte b:arr)
{
System.out.println(b);
}
int id_new = bytes2Int(arr);
System.out.println(id_new);
long id1 = 814312345;
byte arr1[]=Long2Bytes(id1);
for (byte b:arr1)
{
System.out.println(b);
}
long id_new1 = bytes2Long(arr1);
System.out.println(id_new1);
//字符串與字符數組
String name="你不知道我是誰";
byte[] barr= name.getBytes();
String na=new String(barr);
System.out.println(na);
}
}