欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-19 19:29:04
代码如下所示: /*输入一个byte和byte[]合并为byte[]*/ public byte[] bytemerger(byte byte_1, byte...

代码如下所示:

/*输入一个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中byte[]、string、hex字符串等转换的方法,希望对大家有所帮助

上一篇:

下一篇: