【发布时间】:2016-03-09 10:15:23
【问题描述】:
我正在尝试将二进制字符串写入文件,然后读取它并以十六进制表示形式呈现。这是我的代码:
import java.io.*;
import java.math.BigInteger;
public class TestByte {
public static void main(String[] argv) throws IOException {
String bin = "101101010110001000010011000000000100010000000001000000000000000100000000000000000000000000000000000010110000000000111111000101010001100000000000000000000000000000001000000000000000000000111110011111000000000010110011";
//write binary file
DataOutputStream out = null;
File fileout = new File("binout.bin");
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fileout)));
int indx = 0;
for (int i = 0; i < bin.length()/8; i++){
System.out.println(bin.substring(indx, indx+8));
byte[] bytesout = new BigInteger(bin.substring(indx, indx+8),2).toByteArray();
out.write(bytesout);
indx += 8;
}
out.close();
//read binary file
File filein = new File("binout.bin");
byte[] bytesin = new byte[(int) filein.length()];
FileInputStream inputStream = new FileInputStream(filein);
inputStream.read(bytesin);
inputStream.close();
StringBuilder sb = new StringBuilder();
for (byte b : bytesin) {
sb.append(String.format("%02X ", b));
}
System.out.println(sb.toString());
}}
该程序有效,但是与数据存在一些不一致之处。 这是输出:
10110101 01100010 00010011 00000000 01000100 00000001 00000000 00000001 00000000 00000000 00000000 00000000 00001011 00000000 00111111 00010101 00011000 00000000 00000000 00000000 00001000 00000000 00000000 00111110 01111100 00000000 10110011
00 B5 62 13 00 44 01 00 01 00 00 00 00 0B 00 3F 15 18 00 00 00 08 00 00 3E 7C 00 00 B3
如您所见,我已将二进制字符串分解为 8 位片段,以便更容易跟踪数字。不一致的是十六进制表示。十六进制字符串的开头似乎有一个额外的“00”,它不应该存在。字符串末尾还有一个额外的“00”,在“B3”之前应该只有一个“00”。
谁能阐明这个问题和/或使解决方案更优雅?任何帮助,将不胜感激。谢谢。
【问题讨论】:
-
那是哪个 Java 版本?
-
这是JDK版本jdk1.8.0_66 java版本是8更新73
-
问题是
BigInteger是有符号的 (two's complement) 并且需要一个0位来指示正数,当您转换 8 位(无符号)时,您将得到一个 9 位有符号整数。解决方案:不要使用 BigInteger 之类的 hack,自己实现位移。 -
@DanyLavrov 可以使用简单的 int;你可以
Integer.parseInt(someString, 2)然后写(byte) (theInt & 0xff)。顺便说一句,您不需要DataOuputStream:只需使用普通的ÒutputStream和.write()单个字节
标签: java binary hex binaryfiles dataoutputstream