二進制和字符串之間的轉換(包含一些小知識點運用)

package io.transformBinaryString;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


/**
 * 今天在網上看到一個程序遊戲,主要目的是爲了能夠將文件中的字符串讀取到程序,然後通過base64解碼,再轉換成二進制輸出
 * 所以,自己寫了個程序:(1)將一段字符串進行base64處理,然後轉換成二進制輸出。(2)將一段二進制數據轉換成字符串,然後base64解碼到對應的字符串
 * 
 */
public class TransformBS {
	/**
	* @see 字符串進行base64編碼後轉換爲二進制形式,如:(h(原字符)->a(編碼後)->01100001010000010011110100111101(二進制形式))
	*/
	@Test
	public void testS2B(){
		System.out.println("=========字符串到二進制!=============");
		BASE64Encoder e = new BASE64Encoder();//編碼器
		String s = "hello World!";
		System.out.println("尚未編碼的數據:"+s);
		s = e.encode(s.getBytes());//獲得base64編碼後的字符串
		System.out.println("編碼後的數據:"+s);
		System.out.print("二進制數據:");
		for(char c:s.toCharArray()){//對字符串中的字符逐個轉換成二進制數據
			String binaryStr = Integer.toBinaryString(c);//單個字符轉換成的二進制字符串
			String format = String.format("%8s",binaryStr);//因爲上面轉換成二進制後的位數不夠8位所以不足的前面補空格,這裏是考慮到能夠從數據文件批量讀取。
			format =format.replace(" ","0");//高位空格替換成0,其實編碼後的數據最大範圍爲2的6次方,首位一定是空格,不然就要用format.startWith(" ");來判斷
			System.out.print(format);//輸出
		}
		System.out.println("\n=========字符串到二進制結束!=============");
	}
	/**
	* @see 二進制形式轉換爲字符串後進行base64解碼的字符串如:(01100001010000010011110100111101->a->h)
	*/
	@Test
	public void testB2S() throws IOException{
		System.out.println("=========二進制到字符串開始!=============");
		StringBuffer results = new StringBuffer();//保存尚未解碼的數據結果
		String binaryStr= "01100001010001110101011001110011011000100100011100111000011001110101011000110010001110010111100101100010010001110101000101101000";//二進制數據,這裏是取用上面程序的最後結果
		System.out.println("二進制數據:"+binaryStr);
		//這裏採用正則表達式來匹配8位長度的數據,然後一個個find()
		Matcher matcher = Pattern.compile("\\d{8}").matcher(binaryStr);//定義匹配模式並,獲取模式
		BASE64Decoder d = new BASE64Decoder();//解碼器
		while(matcher.find()){//在binaryStr中找到了8位長度的數據,依次往後面找
			int intVal = Integer.valueOf(matcher.group(),2);//matcher.group()中存儲了找到匹配模式的數據,這裏以2進制的形式轉換爲整數
			results.append((char)intVal);//將整數轉換爲對應的字符,並添加到結果中
		}
		System.out.println("尚未解碼的數據:"+results);//輸出尚未解碼的數據
		String s = new String(d.decodeBuffer(results.toString()));//得到解碼後的數據
		System.out.println("解碼後的數據:"+s);//輸出解碼後的數據
		System.out.println("=========二進制到字符串結束!=============");
	}
}



運行效果:

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章