概述
1. 字节数组转十六进制表示的字符串
public static String bytes2HexStr(byte[] byteArr){
if(null==byteArr || byteArr.length<=0){
return null;
}
StringBuffer buf = new StringBuffer("");
for(int i=0; i<byteArr.length; i++){
int byte=byteArr[i] & 0xFF;
String hex=Integer.toHexString(byte);
if(hex.length()<2){
buf.append(0);
}
buf.append(hex);
}
return buf.toString();
}
2. 十六进制表示的字符串转字节数组
public static byte[] hexStr2Bytes(String hexStr){
if(null==hexStr || hexStr.length()<=0){
return null;
}
hexStr=hexStr.toUpperCase();
int len=hexStr.length()/2;
char[] hexChars=hexStr.toCharArray();
byte[] retByte=new byte[len];
for(int i=0; i<len; i++){
int pos=i*2;
retByte[i]=(byte)(charTobyte(hexChars[pos])<<4 | charToByte(hexChars[pos+1]));
}
return retByte;
}
private static byte charToByte(char c){
return (byte)"0123456789ABCDEF".indexOf(c);
}
最后
以上就是娇气铅笔为你收集整理的Java 字节数组与十六进制表示的字符串,互相转换的全部内容,希望文章能够帮你解决Java 字节数组与十六进制表示的字符串,互相转换所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复