byte[] 转 16进制字符串 及 16进制字符串转int

public class HtoInt {
private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
'f' };


public static void main(String[] arts) {
// String hex = "0x00AA00";
// String number = hexToTen(hex);
// System.out.println("number:" + number);
byte[] orders = new byte[]{0x11,0x11,0x10,0x06,0x00,0x00,0x00,0x33,0x01,0x02,0x53,(byte) 0xC3,(byte) 0x78,0x16};
byte[] order = new byte[] { 01, 03, 00, 00, 00, 05, (byte) 0x85, (byte) 0xC9 };


   System.out.println("fun1-->" + bytesToHexFun1(order));
   System.out.println("fun2-->" +bytesToHexFun2(order));
   System.out.println("fun3-->" +bytesToHexFun3(order));


}


/**
* 方法一: byte[] to hex string

* @param bytes
* @return
*/
public static String bytesToHexFun1(byte[] bytes) {
// 一个byte为8位,可用两个十六进制位标识
char[] buf = new char[bytes.length * 2];
int a = 0;
int index = 0;
for (byte b : bytes) { // 使用除与取余进行转换
if (b < 0) {
a = 256 + b;
} else {
a = b;
}


buf[index++] = HEX_CHAR[a / 16];
buf[index++] = HEX_CHAR[a % 16];
}


return new String(buf);
}


/**
* 方法二: byte[] to hex string

* @param bytes
* @return
*/
public static String bytesToHexFun2(byte[] bytes) {
char[] buf = new char[bytes.length * 2];
int index = 0;
for (byte b : bytes) { // 利用位运算进行转换,可以看作方法一的变种
buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
buf[index++] = HEX_CHAR[b & 0xf];
}


return new String(buf);
}


/**
* 方法三: byte[] to hex string

* @param bytes
* @return
*/
public static String bytesToHexFun3(byte[] bytes) {
StringBuilder buf = new StringBuilder(bytes.length * 2);
for (byte b : bytes) { // 使用String的format方法进行转换
buf.append(String.format("%02x", new Integer(b & 0xff)));
}


return buf.toString();
}


/**
* 将16进制字符串转换为byte[]

* @param str
* @return
*/
public static byte[] toBytes(String str) {
if (str == null || str.trim().equals("")) {
return new byte[0];
}


byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length() / 2; i++) {
String subStr = str.substring(i * 2, i * 2 + 2);
bytes[i] = (byte) Integer.parseInt(subStr, 16);
}


return bytes;
}


/**
* 10进制转换成16进制字符串

* @param number
* @return
*/
public static String tenToHex(Integer number) {


return number.toHexString(number);


}


/**
* 16进制字符串转换为10进制字符串

* @param hex
* @return
*/
public static String hexToTen(String hex) {
Integer x;
if (hex.startsWith("0x")) {
x = Integer.parseInt(hex.substring(2), 16);
} else {
x = Integer.parseInt(hex, 16);
}


return x.toString();
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值