JAVAにおける16進数と文字列の変換
3266 ワード
public static String toHexString(int i) 。
, 232; 。 ( 16) 0 ASCII 。 , '0' (’\u0030’) ; , 。 :
0123456789abcdef
'\u0030' '\u0039' '\u0061' '\u0066'。 , String.toUpperCase() :
Integer.toHexString(n).toUpperCase()
:
i - 。
:
( 16) 。
//
public static String toHexString(String s)
{
String str="";
for (int i=0;i<s.length();i++)
{
int ch = (int)s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
//
public static String toStringHex(String s)
{
byte[] baKeyword = new byte[s.length()/2];
for(int i = 0; i < baKeyword.length; i++)
{
try
{
baKeyword[i] = (byte)(0xff & Integer.parseInt(s.substring(i*2, i*2+2),16));
}
catch(Exception e)
{
e.printStackTrace();
}
}
try
{
s = new String(baKeyword, "utf-8");//UTF-16le:Not
}
catch (Exception e1)
{
e1.printStackTrace();
}
return s;
}
//
public static String toStringHex(String s)
{
byte[] baKeyword = new byte[s.length()/2];
for(int i = 0; i < baKeyword.length; i++)
{
try
{
baKeyword[i] = (byte)(0xff & Integer.parseInt(s.substring(i*2, i*2+2),16));
}
catch(Exception e)
{
e.printStackTrace();
}
}
try
{
s = new String(baKeyword, "utf-8");//UTF-16le:Not
}
catch (Exception e1)
{
e1.printStackTrace();
}
return s;
}
public static void main(String[] args) {
System.out.println(encode(" "));
System.out.println(decode(encode(" ")));
}
/*
* 16
*/
private static String hexString="0123456789ABCDEF";
/*
* 16 , ( )
*/
public static String encode(String str)
{
//
byte[] bytes=str.getBytes();
StringBuilder sb=new StringBuilder(bytes.length*2);
// 2 16
for(int i=0;i<bytes.length;i++)
{
sb.append(hexString.charAt((bytes[i]&0xf0)>>4));
sb.append(hexString.charAt((bytes[i]&0x0f)>>0));
}
return sb.toString();
}
/*
* 16 , ( )
*/
public static String decode(String bytes)
{
ByteArrayOutputStream baos=new ByteArrayOutputStream(bytes.length()/2);
// 2 16
for(int i=0;i<bytes.length();i+=2)
baos.write((hexString.indexOf(bytes.charAt(i))<<4 |hexString.indexOf(bytes.charAt(i+1))));
return new String(baos.toByteArray());