字符串(中文英文)转二进制及二进制转回字符串(中文英文)--加密准备
几个月之前,打算写个简单的加密用于项目,总算腾出点时间。在处理第一步字符串转二进制并反转时,以为有简单现成的,结果国内看了看都不太好使(没找到),8位和16位同时处理总有点bug。前一天弄了几个小时没弄好,先干工其他的了。今早,感觉可以,一小会就搞定了,分开处理一下就好了。有需要做相关处理的,供参考。废话不多说了,直接上代码:
1 import java.io.UnsupportedEncodingException; 2 3 public class EncryptionPrepare { 4 /* 5 * 转为二进制 6 */ 7 public static String toBinary(String str,String split){ 8 9 char[] strChar=str.toCharArray(); 10 StringBuffer tempStr=new StringBuffer(); 11 int length=strChar.length; 12 for(int i=0;i<length;i++){ 13 tempStr.append(Integer.toBinaryString(strChar[i])); 14 tempStr.append(split); 15 } 16 return tempStr.toString(); 17 } 18 /* 19 * 转成中英文 20 */ 21 public static String toNormalStr(String str){ 22 byte[] bs = new byte[str.length() / 2]; 23 int len = bs.length; 24 if (len == 1) { 25 bs[0] = (byte) Integer.parseInt(str.substring(0, 2), 16); 26 try { 27 return new String(bs, "utf-8"); 28 } catch (UnsupportedEncodingException e) { 29 e.printStackTrace(); 30 } 31 }else if (len == 2) { 32 for (int i = 0; i < len; i++) { 33 bs[i] = (byte) Integer.parseInt( 34 str.substring(i<<1, (i<<1) + 2), 16);
35 } 36 try { 37 return new String(bs, "utf-16"); 38 } catch (UnsupportedEncodingException e) { 39 e.printStackTrace(); 40 } 41 } 42 return "wrong"; 43 44 } 45 /* 46 * 获取中英文 47 */ 48 public static String getNormalStr(String str,String split){ 49 String[] tempStr = StrToStrArray(str,split); 50 StringBuffer strBuffer=new StringBuffer(); 51 int len=tempStr.length; 52 for (int i = 0; i < len; i++) { 53 strBuffer.append(toNormalStr(Integer.toHexString(Integer.parseInt(tempStr[i], 2)))); 54 } 55 return strBuffer.toString(); 56 57 } 58 /* 59 * 以不同字符分割 60 */ 61 private static String[] StrToStrArray(String str,String split) { 62 return str.split(split); 63 } 64 //测试 65 public static void main(String[] args) throws UnsupportedEncodingException { 66 System.out.println(EncryptionPrepare.toBinary("1网this测试一下jk%"," ")); 67 System.out.println(EncryptionPrepare.getNormalStr("110001 111111101010001 1110100 1101000 1101001 1110011 110110101001011 1000101111010101 100111000000000 100111000001011 1101010 1101011 100101"," ")); 68 69 } 70 }