说明:用日文charset shift-jis(汉字假名占2byte,英文数字占1byte)实现的。
java 代码
- import java.io.UnsupportedEncodingException;
- public class CharStr {
- private static String hex2Str(String theHex) {
- String theRst = "";
- byte[] theByte = new byte[theHex.length() / 2];
- try {
- for (int i = 0; i < theHex.length(); i += 2) {
- theByte[i / 2 ] = Integer.decode("0X"+
- theHex.substring(i, i + 2)).byteValue();
- }
- theRst = new String(theByte, 0, theByte.length, "Shift_JIS");
- } catch (Exception Ue) {
- Ue.printStackTrace();
- }
- return theRst;
- }
- private static String str2Hex(String theStr) {
- byte[] bytes;
- String result = "";
- int tmp;
- String tmpStr;
- try {
- bytes = theStr.getBytes("Shift_JIS");
- for (int i = 0; i < bytes.length; i++) {
- if (bytes[i] < 0) {
- tmp = 256 + bytes[i];
- tmpStr = Integer.toHexString(tmp).toUpperCase();
- result += tmpStr;
- } else {
- tmpStr = Integer.toHexString(bytes[i]).toUpperCase();
- result += tmpStr.length()==1?"0"+tmpStr:tmpStr;
- }
- }
- } catch (UnsupportedEncodingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return result;
- }
- public static void main(String[] argv) throws UnsupportedEncodingException {
- String a = "abcdefあaいbうcえdおe";
- String b = str2Hex(a);
- String c = hex2Str(b);
- System.out.println(a);
- System.out.println(b);
- System.out.println(c);
- }
- }