Java 字串,byte[],16進位的字串互轉

來源:互聯網
上載者:User

 /**

* 字串轉換成十六進位字串

*/

public static String str2HexStr(String str) {

char[] chars = "0123456789ABCDEF".toCharArray();

StringBuilder sb = new StringBuilder("");

byte[] bs = str.getBytes();

int bit;

for (int i = 0; i < bs.length; i++) {

bit = (bs[i] & 0x0f0) >> 4;

sb.append(chars[bit]);

bit = bs[i] & 0x0f;

sb.append(chars[bit]);

}

return sb.toString();

}

/**

* 十六進位轉換字串

*/

public static String hexStr2Str(String hexStr) {

String str = "0123456789ABCDEF";

char[] hexs = hexStr.toCharArray();

byte[] bytes = new byte[hexStr.length() / 2];

int n;

for (int i = 0; i < bytes.length; i++) {

n = str.indexOf(hexs[2 * i]) * 16;

n += str.indexOf(hexs[2 * i + 1]);

bytes[i] = (byte) (n & 0xff);

}

return new String(bytes);

}

/**
* bytes轉換成十六進位字串
*/
public static String byte2HexStr(byte[] b) {
String hs="";
String stmp="";
for (int n=0;n<b.length;n++) {
stmp=(Integer.toHexString(b[n] & 0XFF));
if (stmp.length()==1) hs=hs+"0"+stmp;
else hs=hs+stmp;
//if (n<b.length-1) hs=hs+":";
}
return hs.toUpperCase();
}

private static byte uniteBytes(String src0, String src1) {
byte b0 = Byte.decode("0x" + src0).byteValue();
b0 = (byte) (b0 << 4);
byte b1 = Byte.decode("0x" + src1).byteValue();
byte ret = (byte) (b0 | b1);
return ret;
}

/**
* bytes轉換成十六進位字串
*/
public static byte[] hexStr2Bytes(String src) {
int m=0,n=0;
int l=src.length()/2;
System.out.println(l);
byte[] ret = new byte[l];
for (int i = 0; i < l; i++) {
m=i*2+1;
n=m+1;
ret[i] = uniteBytes(src.substring(i*2, m),src.substring(m,n));
}
return ret;
}

/**
*String的字串轉換成unicode的String
*/
public static String stringToUnicode(String strText) throws Exception {
char c;
String strRet = "";
int intAsc;
String strHex;
for (int i = 0; i < strText.length(); i++) {
c = strText.charAt(i);
intAsc = (int) c;
strHex = Integer.toHexString(intAsc);
if (intAsc > 128) {
strRet += "\\u" + strHex;
} else {
// 低位在前面補00
strRet += "\\" + strHex;
}
}
return strRet;
}
/**
*unicode的String轉換成String的字串
*/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.