gpt4 book ai didi

java - 二进制文件读取不正确

转载 作者:行者123 更新时间:2023-12-01 23:55:09 25 4
gpt4 key购买 nike

我正在尝试将二进制文件转换为基数 10,但是当我将二进制文件的内容传输到数组列表时,我得到的是 48,而不是 0,得到的是 49,而不是 1。

import java.io.*;
import java.util.ArrayList;

public class BaseToDecimal {
public static void main(String[] args) throws IOException,
FileNotFoundException{

//Reads in a binary file
FileInputStream binFile = new FileInputStream("file1.bin");
BufferedInputStream bufferedFile = new BufferedInputStream(binFile, 1000);

//Puts each element from the file into an arraylist
ArrayList<Integer> binaryList = new ArrayList<Integer>();
int current = bufferedFile.read();
while(current != -1){
binaryList.add(current);
current = bufferedFile.read();
}

//Converts binary from arraylist to base 10
int result = 0;
for(int i = 0; i <= binaryList.size() - 1; i++){
result = (result * 2) + binaryList.get(i);
}

//prints out original binary number, number of bytes, and base 10 conversion
System.out.print("File content: ");
for(int i = 0; i <= binaryList.size() - 1; i++){
System.out.print(binaryList.get(i));
}
System.out.println("");
System.out.println("Total number of bytes read: " + (binaryList.size())+ " bytes");
System.out.println("The equivalent number in base 10 format is " + result);
}
}

二进制文件只是 1011101011111011,但是当读入数组列表时,我得到 49484949494849484949494949484949

最佳答案

您的文件正在被读取为文本数据 (ASCII),并且正在传递字符代码的整数值。您将需要根据提供的值创建一个字符,然后将其解析为字符串以检索每个字符表示的值。

关于java - 二进制文件读取不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58205300/

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