今天在測試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; } }