溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java中byte[]、String、Hex字符串等轉(zhuǎn)換的方法

發(fā)布時(shí)間:2020-10-25 04:21:25 來(lái)源:腳本之家 閱讀:310 作者:mrr 欄目:編程語(yǔ)言

代碼如下所示:

/*輸入一個(gè)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; 
 } 
/*輸入一個(gè)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; 
 } 
/*輸入一個(gè)string(16進(jìn)制的字符hex eg:ff)輸出為16進(jìn)制的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進(jìn)制數(shù)字字符串,輸出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進(jìn)制byte[]輸出16進(jìn)制字符串*/ 
 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對(duì)url中特殊字符的轉(zhuǎn)換

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)); 

總結(jié)

以上所述是小編給大家介紹的Java中byte[]、String、Hex字符串等轉(zhuǎn)換的方法,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI