62,614
社区成员
发帖
与我相关
我的任务
分享
public static byte uniteBytes(byte src0, byte src1)
{
byte _b0 = Byte.decode("0x" + new String(new byte[]{src0})).byteValue();
_b0 = (byte)(_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[]{src1})).byteValue();
byte ret = (byte)(_b0 | _b1);
return ret;
}
public static byte[] HexString2Bytes(String src) //十六进制转byte
{
byte[] tmp = src.getBytes();
byte[] ret = new byte[tmp.length/2];
for(int i=0; i<ret.length; i++){
ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]);
}
return ret;
}
public static String byte2HexString(byte[] b) {
char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char[] newChar = new char[b.length * 2];
for(int i = 0; i < b.length; i++) {
newChar[2 * i] = hex[(b[i] & 0xf0) >> 4];
newChar[2 * i + 1] = hex[b[i] & 0xf];
}
return new String(newChar);
}
public static String Bytes2HexString(byte[] b) //byte转换为十六进制
{
String ret = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i]& 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex.toUpperCase();
}
return ret;
}
public class Test {
public static void main(String args[]) {
String str = "Hello";
byte[] b = str.getBytes();
String s = byte2HexString(b);
System.out.println(s);
System.out.println(new String(hexString2ByteArray(s)));
}
public static String byte2HexString(byte[] b) {
char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char[] newChar = new char[b.length * 2];
for(int i = 0; i < b.length; i++) {
newChar[2 * i] = hex[(b[i] & 0xf0) >> 4];
newChar[2 * i + 1] = hex[b[i] & 0xf];
}
return new String(newChar);
}
public static byte[] hexString2ByteArray(String hexString) {
if(hexString.length() % 2 != 0) {
throw new IllegalArgumentException("error");
}
char[] chars = hexString.toCharArray();
byte[] b = new byte[chars.length / 2];
for(int i = 0; i < b.length; i++) {
int high = Character.digit(chars[2 * i], 16) << 4;
int low = Character.digit(chars[2 * i + 1], 16);
b[i] = (byte)(high | low);
}
return b;
}
}
public class Test {
public static void main(String args[]) {
String str = "Hello";
byte[] b = str.getBytes();
System.out.println(byte2HexString(b));
}
public static String byte2HexString(byte[] b) {
char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char[] newChar = new char[b.length * 2];
for(int i = 0; i < b.length; i++) {
newChar[2 * i] = hex[(b[i] & 0xf0) >> 4];
newChar[2 * i + 1] = hex[b[i] & 0xf];
}
return new String(newChar);
}
}