java 16进制字符串转16进制

本文介绍了一种在Java中实现十六进制字符串与字节数组相互转换的方法。通过定义`HexString2Bytes`和`Bytes2HexString`两个函数,实现了字符串与字节数组之间的灵活转换,并提供了示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


/**
* @author yaodaqing == 姚大庆
*/
public class Test {

public static void main(String[] args) {
byte[] b = HexString2Bytes("AA020155");
String s = Bytes2HexString(b);
System.out.println(s);
}

/**
* 将两个ASCII字符合成一个字节;
* 如:"EF"--> 0xEF
* @param src0 byte
* @param src1 byte
* @return byte
*/
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;
}

/**
* 将指定字符串src,以每两个字符分割转换为16进制形式
* 如:"2B44EFD9" –> byte[]{0x2B, 0×44, 0xEF, 0xD9}
* @param src String
* @return byte[]
*/
public static byte[] HexString2Bytes(String src){
byte[] ret = new byte[src.length()/2];
byte[] tmp = src.getBytes();
for(int i=0; i< tmp.length/2; i++){
ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]);
}
return ret;
}

/**
* 将指定byte数组以16进制的形式打印到控制台
* @param hint String
* @param b byte[]
* @return void
*/
public static void printHexString(String hint, byte[] b) {
System.out.print(hint);
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
System.out.print(hex.toUpperCase() + " ");
}
System.out.println("");
}

/**
*
* @param b byte[]
* @return String
*/
public static String Bytes2HexString(byte[] b) {
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;
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值