网站首页 语言 会计 电脑 医学 资格证 职场 文艺体育 范文
当前位置:书香门第 > IT认证 > JAVA认证

JAVA十六进制与字符串的转换方法

栏目: JAVA认证 / 发布于: / 人气:7.55K

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

}