Java字符串跟ASCII码互转
1.由于项目中遇到,在服务器端起的jar包程序,给前台发消息后,前段收到的消息出现乱码情况,所以采取在后才发消息前先把消息字符串转成ASCII码再发往前台,前台采取在收到后台消息先把ASCII码转成字符串的解决方案进行解决。
1)将字符串转成ASCII的Java方法
public static String stringToAscii(String value) { StringBuffer sbu = new StringBuffer(); char[] chars = value.toCharArray(); for (int i = 0; i < chars.length; i++) { if(i != chars.length - 1) { sbu.append((int)chars[i]).append(","); } else { sbu.append((int)chars[i]); } } return sbu.toString(); }
2)将ASCII转成字符串的java方法
public static String asciiToString(String value) { StringBuffer sbu = new StringBuffer(); String[] chars = value.split(","); for (int i = 0; i < chars.length; i++) { sbu.append((char) Integer.parseInt(chars[i])); } return sbu.toString(); }
main方法测试:
public static void main(String[] args) { String str = "{name:1234,password:4444}"; String asciiResult = stringToAscii(str); System.out.println(asciiResult); String stringResult = asciiToString(asciiResult); System.out.println(stringResult); }
输出:
123,110,97,109,101,58,49,50,51,52,44,112,97,115,115,119,111,114,100,58,52,52,52,52,125
{name:1234,password:4444}