八位二进制数批量转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 。

 

转载于:https://www.cnblogs.com/Lowp/archive/2012/11/16/2774211.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值