test2.java
2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.huaheng.test;
public class test2 {
//int转byte[] 高字节在前(高字节序)
public static byte[] toByteArray(int n) {
byte[] b = new byte[4];
b[3] = (byte) (n & 0xff);
b[2] = (byte) (n >> 8 & 0xff);
b[1] = (byte) (n >> 16 & 0xff);
b[0] = (byte) (n >> 24 & 0xff);
return b;
}
//int的二进制表示 高字节在前(高字节序)
public static StringBuilder intToBinary(int num){
StringBuilder str = new StringBuilder();
// for(int i=31;i>=0;i--){
// str.append((num & (1 <<i))==0?"0":"1");
// }
for(int i=15;i>=0;i--){
str.append((num & (1 <<i))==0?"0":"1");
}
// System.out.println();
return str;
}
//byte数组的二进制表示
public static String byteArrayToBinary(byte[] bytes){
StringBuilder str = new StringBuilder();
for (byte b : bytes) {
String tString = Integer.toBinaryString((b & 0xFF) + 0x100).substring(1);
str.append(tString);
}
System.out.println(str.toString());
return str.toString();
}
public static void main(String[] args) {
int a=512;
int bit=9;
// intToBinary(a);
// intToBinary(a>>1);
// byte[] bytes = toByteArray(256);
// byteArrayToBinary(bytes);
//System.out.println(intBitArithmetic(a,bit));
}
//用于写 num读到的值,bit往哪个位写值,flag写几0/1
public static int xie(int num,int bit,String flag){
StringBuilder stringBuilder = intToBinary(256);
stringBuilder.replace(15-bit,16-bit,flag);
return Integer.parseInt(stringBuilder.toString(), 2);
}
//int类型时 进行位运算,位移多少位 用于读
public static boolean intBitArithmetic(int num,int bit){
if(num==(num & (1 << bit))){
return true;
}else {
return false;
}
}
//字符串转二进制
public static String toBinary(String str)
{
char[] strChar = str.toCharArray();
int [] a=new int[str.length()];
for(int i=0;i<str.length();i++)
{
a[i]=strChar[i];
}
String result = "";
for(int i = 0; i < strChar.length; i++)
{
if(Integer.toBinaryString(a[i]).length()<7)
{
result+="0"+Integer.toBinaryString(a[i])+" ";
}
else
{
result += Integer.toBinaryString(a[i]) + " ";
}
}
return result;
}
}