gpt4 book ai didi

java - 从 bin 文件中读取整数对大于 256 的数字执行 modulu(256)

转载 作者:行者123 更新时间:2023-12-02 04:39:02 25 4
gpt4 key购买 nike

我正在尝试从 bin 文件中读取数字,当它到达大于 256 的数字时,它会对该数字执行 modulu(256) ,例如:我试图读取的数字是 258,从文件中读取的数字是 (2) => 258mod256=2我怎样才能读到完整的数字?这是代码片段:

InputStream ReadBinary = new BufferedInputStream(new FileInputStream("Compressed.bin"));
int BinaryWord = 0;
while(BinaryWord != -1) {
BinaryWord = ReadBinary.read();
if(BinaryWord != -1)
System.out.println(BinaryWord + ": " + Integer.toBinaryString(BinaryWord));

写入文件的代码:

        DataOutputStream binFile = new DataOutputStream(new FileOutputStream("C:\\Users\\George Hanna\\eclipse-workspace\\LZW\\Compressed.bin"));
//convert codewords to binary to send them.
for(int i=0;i<result.size();i++)
try {
IOFile.print(Integer.toBinaryString(result.get(i))+ " ");
binFile.writeByte(result.get(i));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
binFile.close();

最佳答案

只是提供一些有关整数如何存储的背景知识:

总而言之,您的文件由字节组成。每个字节的值都在 0 到 255 之间。

要表示 32 位 int,需要 4 个字节。

Java有int(4字节)和long(8字节)。

在二进制文件中存储数据的最简单方法是使用DataOutputStream,并使用DataInputStream读取它。它将为您处理所有这些转换。

DataOutputStream out = new DataOutputStream(new FileOutputStream("intFile.bin"));
out.writeInt(123456789);
out.close();

DataInputStream in = new DataInputStream(new FileInputStream("intFile.bin"));
System.out.println(in.readInt());
in.close();

要从文件中获取单个字节,请执行以下操作:

InputStream in_bytes = new FileInputStream("intFile.bin");
int nextByte = in_bytes.read();
while(nextByte != -1) {
System.out.println(nextByte);
nextByte = in_bytes.read();
}
in_bytes.close();

要将单个字节写入文件,请执行以下操作:

OutputStream out_bytes = new FileOutputStream("intFile.bin");
out_bytes.write(1);
out_bytes.write(2);
out_bytes.write(3);
out_bytes.write(4);
out_bytes.close();

但是正如您已经意识到的,您在这里写入的是字节,因此您的范围被限制在 0 到 255 之间。

关于java - 从 bin 文件中读取整数对大于 256 的数字执行 modulu(256),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56529307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com