import io.netty.buffer.ByteBuf;
import java.math.BigInteger;
public class ByteConvertUtil {
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[] intToBytes2(int value) {
byte[] src = new byte[4];
src[0] = (byte) ((value >> 24) & 0xFF);
src[1] = (byte) ((value >> 16) & 0xFF);
src[2] = (byte) ((value >> 8) & 0xFF);
src[3] = (byte) (value & 0xFF);
return src;
}
public static int bytesToInt(byte[] src, int offset) {
int value;
value = (int) ((src[offset] & 0xFF)
| ((src[offset + 1] & 0xFF) << 8)
| ((src[offset + 2] & 0xFF) << 16)
| ((src[offset + 3] & 0xFF) << 24));
return value;
}
public static int bytesToInt2(byte[] src, int offset) {
int value;
value = (int) (((src[offset] & 0xFF) << 24)
| ((src[offset + 1] & 0xFF) << 16)
| ((src[offset + 2] & 0xFF) << 8)
| (src[offset + 3] & 0xFF));
return value;
}
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;
}
public static String bytes2HexString(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
int first = (bytes[i] & 0xFF) >> 4;
int second = (bytes[i] & 0xFF) & 0x0F;
sb.append(int2Char(first));
sb.append(int2Char(second));
}
return sb.toString();
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
private static char int2Char(int data) {
String str = "0123456789ABCDEF";
return str.charAt(data);
}
public static byte getCheckResult(byte[] bytes) {
byte result = bytes[0];
for (int i = 1; i < bytes.length; i++) {
result ^= bytes[i];
}
return result;
}
public static String addBinary(String a, String b) {
String result = "";
int sum = 0;
int lengthA = a.length();
int lengthB = b.length();
while (lengthA > 0 || lengthB > 0) {
if (lengthA > 0) {
sum += Integer.parseInt(a.substring(lengthA - 1, lengthA));
lengthA--;
}
if (lengthB > 0) {
sum += Integer.parseInt(b.substring(lengthB - 1, lengthB));
lengthB--;
}
if (sum == 2) {
result = "0" + result;
sum = 1;
} else if (sum == 3) {
result = "1" + result;
sum = 1;
} else {
result = (sum + "") + result;
sum = 0;
}
}
if (sum == 1) {
result = "00000001" + result;
}
return result;
}
public static String getAddResultForBytes(ByteBuf udpcontent) {
udpcontent.markReaderIndex();
String jyh = new BigInteger(1, new byte[]{udpcontent.readByte()}).toString(2);
for (int i = 1; i < 63; i++) {
String tmp = new BigInteger(1, new byte[]{udpcontent.readByte()}).toString(2);
jyh = addBinary(jyh, tmp);
}
udpcontent.resetReaderIndex();
return jyh;
}