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;
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论