欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Java中byte[]、String、Hex字符串等转换的方法

时间:2021-01-05 13:45:38|栏目:JAVA代码|点击:

代码如下所示:

/*输入一个byte和byte[]合并为byte[]*/ 
public byte[] byteMerger(byte byte_1, byte[] byte_2) { 
 byte[] byte_3 = new byte[1 + byte_2.length]; 
 byte_3[0] = byte_1; 
 System.arraycopy(byte_2, 0, byte_3, 1, byte_2.length); 
 return byte_3; 
 } 
/*输入一个byte[]和byte[]合并为byte[]*/ 
public byte[] byteMerger(byte[] byte_1, byte[] byte_2) { 
 byte[] byte_3 = new byte[1 + byte_2.length]; 
 byte_3[0] = byte_1; 
 System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length); 
 return byte_3; 
 } 
/*输入一个string(16进制的字符hex eg:ff)输出为16进制的byte[],注意输入为小写的hex字符串*/ 
public byte[] hexStringToByte(String hex) { 
 int len = (hex.length() / 2); 
 byte[] result = new byte[len]; 
 char[] achar = hex.toCharArray(); 
 for (int i = 0; i < len; i++) { 
  int pos = i * 2; 
  result[i] = (byte) (charToByte(achar[pos]) << 4 | charToByte(achar[pos + 1])); 
 } 
 //System.out.println(Arrays.toString(result)); 
 return result; 
 } 
 private byte charToByte(char c) { 
 //return (byte) "0123456789ABCDEF".indexOf(c); 
 return (byte) "0123456789abcdef".indexOf(c); 
 } 
/*输入10进制数字字符串,输出hex字符串(2位,eg: f 则输出 0f)*/ 
String value= "100"; 
int parseInt = Integer.parseInt(value, 10); 
String hexString = Integer.toHexString(parseInt); 
  if (hexString.length() < 2) { 
  hexString = '0' + hexString; 
  } 
  header = header + hexString; 
 } 
/*输入16进制byte[]输出16进制字符串*/ 
 public static String byteArrayToHexStr(byte[] byteArray) { 
 if (byteArray == null) { 
  return null; 
 } 
 char[] hexArray = "0123456789ABCDEF".toCharArray(); 
 char[] hexChars = new char[byteArray.length * 2]; 
 for (int j = 0; j < byteArray.length; j++) { 
  int v = byteArray[j] & 0xFF; 
  hexChars[j * 2] = hexArray[v >>> 4]; 
  hexChars[j * 2 + 1] = hexArray[v & 0x0F]; 
 } 
 return new String(hexChars); 
 } 

PS:下面看下js对url中特殊字符的转换

let str = "http%3A%2F%2Fxxxxxxxx%2Findex.php%2Fxxxxxxx%2FMember%2Fregister%3Frecommend_id%3D11442%26id%3D87"; 
function replaceStr(str){ 
 str = str.replace(/%3A/g, ":"); 
 str = str.replace(/%2F/g, "/"); 
 str = str.replace(/%3F/g, "?"); 
 str = str.replace(/%3D/g, "="); 
 str = str.replace(/%26/g, "&"); 
 str = str.replace(/%2B/g, "+"); 
 str = str.replace(/%20/g, " "); 
 str = str.replace(/%23/g, "#"); 
 return str; 
} 
console.log(replaceStr(str)); 

总结

上一篇:Java方法参数装配顺序详解

栏    目:JAVA代码

下一篇:SpringBoot实现发送短信的示例代码

本文标题:Java中byte[]、String、Hex字符串等转换的方法

本文地址:http://www.codeinn.net/misctech/40711.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有