Java-將文本(字符串)轉化成二進制字符


今天在測試MySQL的Blob相關類型時,這種一般存放的是二進制文本,所以就想插入二進制文本。

package com.aaa.dao;

public class aaa {
   public static void main(String[] args) {

       //轉換就維護main方法里面的兩個注釋就行



       /***
        * 1.字符串轉二進制開始
        * **/
     /*  String str = "谷愛凌";
        char[] strChar=str.toCharArray();
        String result="";
        for(int i=0;i<strChar.length;i++){
            result +=Integer.toBinaryString(strChar[i])+ " ";
        }
        System.out.println(result);*/
       /**
        *1二進制轉字符串結束
        * **/

       /**
        *2. 二進制轉字符串開始
        * */

       String binStr = "111011100011111 110110 1111111100001100 100111101010101 1000110110000101 101100101000111 100111011100101 101010000001110 1000101111110100 1000101111011101 101110000110001 111010100101000 100111010001100 1000111111011011 101001000110110";
       String[] tempStr=binStr.split(" ");
       char[] tempChar=new char[tempStr.length];
       for(int i=0;i<tempStr.length;i++) {
          tempChar[i]=BinstrToChar(tempStr[i]);
       }
       System.out.println(String.valueOf(tempChar));

       /**
        * 2二進制轉字符串結束
        * */
}


   //將二進制轉換成字符
   public static char BinstrToChar(String binStr){
       int[] temp=BinstrToIntArray(binStr);
       int sum=0;
       for(int i=0; i<temp.length;i++){
           sum +=temp[temp.length-1-i]<<i;
       }
       return (char)sum;
  }
 //將二進制字符串轉換成int數組
   public static int[] BinstrToIntArray(String binStr) {
       char[] temp=binStr.toCharArray();
       int[] result=new int[temp.length];
       for(int i=0;i<temp.length;i++) {
           result[i]=temp[i]-48;
       }
       return result;
   }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM