zoukankan      html  css  js  c++  java
  • 八位二进制数批量转unicode码

    这个程序是把一个文件中的二进制数字以8位为一个单位,进行读取,然后进行unicode转义,最后把转义的字符写入另外一个文件

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    
    /**
     * 二级制转为字符码
     */
    public class BinarytoChar {
    	static int count = 0;
    	static int charTemp = 0;
    	File keyFile = new File("D:/Java/keytest.txt");
    	FileInputStream fin;
    	File keyOut = new File("D:/Java/output.txt");
    	RandomAccessFile raf;
    
    	public BinarytoChar() throws IOException {
    		raf = new RandomAccessFile(keyOut, "rw");
    	}
    
    	/**
    	 * 处理的主函数,包括读取文件的字节流
    	 * 
    	 * @throws IOException
    	 */
    	void key() throws IOException {
    		byte buffer[] = new byte[2];
    		fin = new FileInputStream(keyFile);
    		while ((fin.read(buffer, 0, 1)) != -1) {
    			readByte(buffer[0]);
    		}
    		/* 下边的代码还需要执行一次写入,因为readByte()函数最后一次没有执行写入 */
    		char ch = (char) charTemp;
    		raf.seek(raf.length());
    		raf.writeByte(ch);
    	}
    
    	/**
    	 * 传入的是从文件字节流读出的字节,然后处理后写入文件里,使用 & 消去高四位,为递归处理
    	 * 
    	 * @param by
    	 *            输入的字节,从文件读出的字节为6位二进制,格式为<b>11_XXXX</b>
    	 * @throws IOException
    	 */
    	void readByte(byte by) throws IOException {
    		if (count < 8) {
    			by &= 0b001111; // 高位置零
    			int x = (int) by;
    			charTemp += x * (int) Math.pow(2, 7 - count);
    			count++;
    		} else {
    			char ch = (char) charTemp;
    			raf.seek(raf.length());
    			raf.writeByte(ch);
    			count = 0;
    			charTemp = 0;
    			readByte(by);
    		}
    
    	}
    
    	public static void main(String[] args) {
    		try {
    			new BinarytoChar().key(); 
    		} catch (IOException e) {
    			// TODO 自动生成的 catch 块
    			e.printStackTrace();
    		}
    	}
    }
    

      keytest.txt中的内容是:011000010110001101100011 ,那么写入到output.txt的字符为 acc 。

  • 相关阅读:
    670. Maximum Swap
    653. Two Sum IV
    639. Decode Ways II
    636. Exclusive Time of Functions
    621. Task Scheduler
    572. Subtree of Another Tree
    554. Brick Wall
    543. Diameter of Binary Tree
    535. Encode and Decode TinyURL
    博客园自定义背景图片
  • 原文地址:https://www.cnblogs.com/Lowp/p/2774211.html
Copyright © 2011-2022 走看看