ByteUtils.java
3.23 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package com.sunvote.util;
/**
* Created by Elvis on 2017/8/15 15:03
* Email:Eluis@psunsky.com
* 版权所有:长沙中天电子设计开发有限公司
* Description: 工具包
*/
public class ByteUtils {
private ByteUtils() {
}
public static String bytesToHexString(byte[] src, int length) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length && i < length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
stringBuilder.append(" ");
}
return stringBuilder.toString();
}
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
stringBuilder.append(" ");
}
return stringBuilder.toString();
}
/**
* Convert hex string to byte[]
*
* @param hexString the hex string
* @return byte[]
*/
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* Convert char to byte
*
* @param c char
* @return byte
*/
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
public static byte[] intToBytes(int value) {
byte[] src = new byte[4];
src[3] = (byte) ((value >> 24) & 0xFF);
src[2] = (byte) ((value >> 16) & 0xFF);
src[1] = (byte) ((value >> 8) & 0xFF);
src[0] = (byte) (value & 0xFF);
return src;
}
public static byte[] int2Bytes(int value) {
byte[] src = new byte[2];
src[0] = (byte) ((value >> 8) & 0xFF);
src[1] = (byte) (value & 0xFF);
return src;
}
public static int bytes2Int(byte[] src) {
int ret = ((src[1] & 0xFF) | ((src[0] & 0xFF) << 8));
return ret;
}
public static boolean compare(byte[] src,byte[] desc){
if(src == null && desc == null){
return true;
}
if(src == null || desc == null){
return false;
}
if(src.length != desc.length){
return false;
}
for(int i= 0 ; i < src.length ; i++){
if(src[i] != desc[i]){
return false;
}
}
return true;
}
}