栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

代码如下所示:

 
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; 
 } 
 
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; 
 } 
 
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); 
 } 
 
String value= "100"; 
int parseInt = Integer.parseInt(value, 10); 
String hexString = Integer.toHexString(parseInt); 
  if (hexString.length() < 2) { 
  hexString = '0' + hexString; 
  } 
  header = header + hexString; 
 } 
 
 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中byte[]、String、Hex字符串等转换的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/140781.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号