最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
java的ByteHex转换实现方式
时间:2026-07-24 09:11:08 编辑:袖梨 来源:一聚教程网
java Byte Hex转换
在byte字节转Hex时需要“& 0xFF”

字节(byte)转十六进制(Hex)
/**
* Byte字节转Hex
* @param b 字节
* @return Hex
*/
public static String byteToHex(byte b)
{
String hexString = Integer.toHexString(b & 0xFF);
//由于十六进制是由0~9、A~F来表示1~16,所以如果Byte转换成Hex后如果是<16,就会是一个字符(比如A=10),通常是使用两个字符来表示16进制位的,
//假如一个字符的话,遇到字符串11,这到底是1个字节,还是1和1两个字节,容易混淆,如果是补0,那么1和1补充后就是0101,11就表示纯粹的11
if (hexString.length() < 2)
{
hexString = new StringBuilder(String.valueOf(0)).append(hexString).toString();
}
return hexString.toUpperCase();
}
字节数组(bytes)转十六进制(Hex)
/**
* 字节数组转Hex
* @param bytes 字节数组
* @return Hex
*/
public static String bytesToHex(byte[] bytes)
{
StringBuffer sb = new StringBuffer();
if (bytes != null && bytes.length > 0)
{
for (int i = 0; i < bytes.length; i++) {
String hex = byteToHex(bytes[i]);
sb.append(hex);
}
}
return sb.toString();
}
十六进制(Hex)转字节(byte)
/**
* Hex转Byte字节
* @param hex 十六进制字符串
* @return 字节
*/
public static byte hexToByte(String hex)
{
return (byte) Integer.parseInt(hex,16);
}
十六进制(Hex)转字节数组(bytes)
/**
* Hex转Byte字节数组
* @param hex 十六进制字符串
* @return 字节数组
*/
public static byte[] hexToBytes(String hex)
{
int hexLength = hex.length();
byte[] result;
//判断Hex字符串长度,如果为奇数个需要在前边补0以保证长度为偶数
//因为Hex字符串一般为两个字符,所以我们在截取时也是截取两个为一组来转换为Byte。
if (hexLength % 2 ==1)
{
//奇数
hexLength++;
hex = "0"+hex;
}
result = new byte[(hexLength/2)];
int j = 0;
for (int i = 0; i < hexLength; i+=2) {
result[j] = hexToByte(hex.substring(i,i+2));
j++;
}
return result;
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持本站。
您可能感兴趣的文章:- Java实现ByteArray与String互转的常见转换方法
- Java实现基本数据类型与byte数组相互转换
- Java中将byte[]转MultipartFile的具体实现方式
- Java中Byte数组与InputStream相互转换实现方式
- Java中的getBytes()方法使用详解
- Java 将 byte[] 转换为 File 对象的具体代码示例