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 。

  • 相关阅读:
    打印二叉树中节点的所有祖先
    1.把2叉查找树转换成双向链表
    Linux下tar.xz结尾的文件的解压方法
    Floyd算法
    c缺陷与陷阱笔记-第七章 可移植性代码
    c缺陷与陷阱笔记-第六章 预处理器
    c缺陷与陷阱笔记-第四章 连接
    C语言小程序(四)、杨辉三角
    C语言小程序(三)、判断两个日期之差
    C语言小程序(二)、计算第二天日期
  • 原文地址:https://www.cnblogs.com/Lowp/p/2774211.html
Copyright © 2011-2022 走看看