this is stringToHexAsciiString.
//将字符串转成ASCII十六进制的java方法
public static String stringToHexAsciiString(String value)
{
StringBuffer sbu = new StringBuffer();
char[] chars = value.toCharArray();
for (int i = 0; i < chars.length; i++)
{
sbu.append(Integer.toHexString(chars[i]));
}
return sbu.toString();
}
这是 asciiToString 开始
//将ASCII转成字符串的java方法
public static String asciiToString(String value)
{
StringBuffer sbu = new StringBuffer();
//System.out.println("value.length()/2 = " + value.length()/2);
byte[] chars = new byte[value.length()/2];
chars = hexStringToByte(value);
//System.out.println("chars.length = " + chars.length);
for(int i=0; i<chars.length; i++){
//sbu.append((char) Integer.parseInt(chars[i]));
byte[] change = new byte[1];
change[0] = chars[i];
//System.out.println("change[0] = " + change[0]);
sbu.append((char) chars[i]);
//System.out.println("i = " + i + " " + sbu.toString());
}
return sbu.toString();
}
public static byte[] hexStringToByte(String hexString){
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 |charToByte(hexChars[pos + 1]));
// d[i] = (byte) (hexChars[pos] << 4 |hexChars[pos + 1]);
}
return d;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
使用测试英语还可以,中文不好。
String strAscii = Encrypter.stringToHexAsciiString("汉1232").trim();
String asciiStr = Encrypter.asciiToString("6c4931323332".toUpperCase());
System.out.println("asciiStr:"+asciiStr);
System.out.println("strAscii:"+strAscii);
asciiToString 结果是中文变得凌乱的代码
asciiStr:lI1232
strAscii:6c4931323332
需要汉1232.stringToHexAsciiString 结果:中文字符为2字节,英文为1字节。如何划分中文十六进制和英文十六进制。
我不知道
你的代码有什么问题......或者你到底想要什么,这在你的问题中不清楚。但是,如果您只想将字符串转换为十六进制格式,则可以尝试以下代码:
import org.apache.commons.codec.binary.Hex;
public class StringToAscii
{
public static void main( String[] args )
{
try {
String s = "汉1232";
System.out.println(s);
String hexString = new String(Hex.encodeHexString(s.getBytes("UTF-8")));
System.out.println(hexString);
String unicode = new String(Hex.decodeHex(hexString.toCharArray()));
System.out.println(unicode);
}catch (Exception e)
{
e.printStackTrace();
}
}
}
我的笔记本电脑上的输出是:
汉1232
e6b18931323332
汉1232