當前位置:才華齋>IT認證>JAVA認證>

JAVA十六進位制與字串的轉換方法

JAVA認證 閱讀(6.85K)

在java程式中,十六進位制與字串是怎麼轉換的呢?下面yjbys小編就為大家分享JAVA十六進位制與字串的轉換方法,一起來看看吧!

JAVA十六進位制與字串的轉換方法

  第一種方法:

  將指定byte陣列以16進位制的形式列印到控制檯

toHexString

public static String toHexString(int i)以十六進位制的無符號整數形式返回一個整數引數的字串表示形式。

如果引數為負,那麼無符號整數值為引數加上 232;否則等於該引數。將該值轉換為十六進位制(基數 16)的無前導 0 的 ASCII 數字字串。如果無符號數的.大小值為零,則用一個零字元 '0' ('u0030') 表示它;否則,無符號數大小的表示形式中的第一個字元將不是零字元。用以下字元作為十六進位制數字:

0123456789abcdef

這些字元的範圍是從 'u0030' 到 'u0039' 和從 'u0061' 到 'u0066'。如果希望得到大寫字母,可以在結果上呼叫 perCase() 方法:

xString(n)perCase()

引數:

i - 要轉換成字串的整數。

返回:

用十六進位制(基數 16)引數表示的無符號整數值的字串表示形式。

// 轉化字串為十六進位制編碼

public static String toHexString(String s)

{

String str="";

for (int i=0;i

{

int ch = (int)At(i);

String s4 = xString(ch);

str = str + s4;

}

return str;

}

// 轉化十六進位制編碼為字串

public static String toStringHex(String s)

{

byte[] baKeyword = new byte[th()/2];

for(int i = 0; i < th; i++)

{

try

{

baKeyword[i] = (byte)(0xff & eInt(tring(i*2, i*2+2),16));

}

catch(Exception e)

{

tStackTrace();

}

}

try

{

s = new String(baKeyword, "utf-8");//UTF-16le:Not

}

catch (Exception e1)

{

tStackTrace();

}

return s;

}

// 轉化十六進位制編碼為字串

public static String toStringHex(String s)

{

byte[] baKeyword = new byte[th()/2];

for(int i = 0; i < th; i++)

{

try

{

baKeyword[i] = (byte)(0xff & eInt(tring(i*2, i*2+2),16));

}

catch(Exception e)

{

tStackTrace();

}

}

try

{

s = new String(baKeyword, "utf-8");//UTF-16le:Not

}

catch (Exception e1)

{

tStackTrace();

}

return s;

}

public static void main(String[] args) {

tln(encode("中文"));

tln(decode(encode("中文")));

}

/*

* 16進位制數字字符集

*/

private static String hexString="0123456789ABCDEF";

/*

* 將字串編碼成16進位制數字,適用於所有字元(包括中文)

*/

public static String encode(String str)

{

//根據預設編碼獲取位元組陣列

byte[] bytes=ytes();

StringBuilder sb=new StringBuilder(th*2);

//將位元組陣列中每個位元組拆解成2位16進位制整數

for(int i=0;i

{

nd(At((bytes[i]&0xf0)>>4));

nd(At((bytes[i]&0x0f)>>0));

}

return ring();

}

/*

* 將16進位制數字解碼成字串,適用於所有字元(包括中文)

*/

public static String decode(String bytes)

{

ByteArrayOutputStream baos=new ByteArrayOutputStream(th()/2);

//將每2位16進位制整陣列裝成一個位元組

for(int i=0;i

e((xOf(At(i))<<4 |xOf(At(i+1))));

return new String(teArray());

}