二進制轉字符串,字符串轉二進制

 1 package com.aaa.dao;
 2 
 3 public class aaa {
 4    public static void main(String[] args) {
 5        
 6        //轉換就維護main方法裏面的兩個註釋就行
 7        
 8        
 9        
10        /***
11         * 1.字符串轉二進制開始
12         * **/ 
13      /*  String str = "真6,何超奇之後說話就用二進制";
14         char[] strChar=str.toCharArray();
15         String result="";
16         for(int i=0;i<strChar.length;i++){
17             result +=Integer.toBinaryString(strChar[i])+ " ";
18         }
19         System.out.println(result);*/
20        /**
21         *1二進制轉字符串結束
22         * **/
23        
24        /**
25         *2. 二進制轉字符串開始
26         * */
27        
28        String binStr = "111011100011111 110110 1111111100001100 100111101010101 1000110110000101 101100101000111 100111011100101 101010000001110 1000101111110100 1000101111011101 101110000110001 111010100101000 100111010001100 1000111111011011 101001000110110";
29        String[] tempStr=binStr.split(" ");
30        char[] tempChar=new char[tempStr.length];
31        for(int i=0;i<tempStr.length;i++) {
32           tempChar[i]=BinstrToChar(tempStr[i]);
33        }
34        System.out.println(String.valueOf(tempChar));
35        
36        /**
37         * 2二進制轉字符串結束
38         * */
39 }
40    
41    
42    
43    
44    
45    
46    
47    
48    //將二進制轉換成字符
49    public static char BinstrToChar(String binStr){
50        int[] temp=BinstrToIntArray(binStr);
51        int sum=0;
52        for(int i=0; i<temp.length;i++){
53            sum +=temp[temp.length-1-i]<<i;
54        }   
55        return (char)sum;
56   }
57  //將二進制字符串轉換成int數組
58    public static int[] BinstrToIntArray(String binStr) {       
59        char[] temp=binStr.toCharArray();
60        int[] result=new int[temp.length];   
61        for(int i=0;i<temp.length;i++) {
62            result[i]=temp[i]-48;
63        }
64        return result;
65    }
66 }
相關文章
相關標籤/搜索