Java中String与二进制码的相互转换

把字符串转成二进制码

public class stringTest {
    public static void main(String[] args) {
        String str = "abc";
        String binary = toBinary(str);
        System.out.println(binary);
    }

    public static String toBinary(String str){
        //把字符串转成字符数组
        char[] strChar=str.toCharArray();
        String result="";
        for(int i=0;i//toBinaryString(int i)返回变量的二进制表示的字符串
            //toHexString(int i) 八进制
            //toOctalString(int i) 十六进制
            result +=Integer.toBinaryString(strChar[i])+ " ";
        }
        return result;
    }
}

结果:abc–>1100001 1100010 1100011

将二进制码转成字符串

public class stringTest {
    public static void main(String[] args) {
        String binary = "1100001 1100010 1100011";      
        System.out.println(toString(binary));
    }

    public static String toString(String binary) {
         String[] tempStr=binary.split(" ");
            char[] tempChar=new char[tempStr.length];
            for(int i=0;ireturn String.valueOf(tempChar);
    }


    //将二进制字符串转换成int数组
    public static int[] BinstrToIntArray(String binStr) {       
        char[] temp=binStr.toCharArray();
        int[] result=new int[temp.length];   
        for(int i=0;i48;
        }
        return result;
    }


    //将二进制转换成字符
    public static char BinstrToChar(String binStr){
        int[] temp=BinstrToIntArray(binStr);
        int sum=0;
        for(int i=0; i1-i]<return (char)sum;
   }
}

结果:1100001 1100010 1100011 –>abc

java源码Integer类:https://blog.csdn.net/u013190513/article/details/70216730

你可能感兴趣的:(String与二进制码互相转换,Java,String与二进制码互相转换)