简体   繁体   English

在Java中读取32位二进制数

[英]Read 32 bit binary numbers in java

I am trying to read five 32-bit binary numbers and print them as int. 我正在尝试读取五个32位二进制数并将其打印为int。 Here is my code: 这是我的代码:

FileInputStream fin = new FileInputStream(file);
        int count = 5;

        for (int i = 0; i < count; i++) {
            byte[] input = file.getBytes();
            String bin=Integer.toBinaryString(0xFF & input[i] | 0x100).substring(1);
            System.out.println(bin);

I am getting this: 我得到这个:

01010011
01101110
00110011
01011111
01010010

What am I doing wrong? 我究竟做错了什么? thanks 谢谢

You're not actually reading from the file, but printing the binary representation of the first five characters of the name of the file. 您实际上并不是从文件中读取文件,而是打印文件名的前五个字符的二进制表示形式。 Use fin.read() to read bytes from the file. 使用fin.read()从文件中读取字节。

You can also use DataInputStream to read 32 bit big endian integers directly, instead of reading them as 4 individual bytes. 您也可以使用DataInputStream直接读取32位大端整数,而不是将其读取为4个单独的字节。

If you need to read five big-endian 32-bit integers, then I suggest that you use DataInputStream , eg 如果您需要读取5 个大端 32位整数,那么我建议您使用DataInputStream ,例如

final int count = 5;

try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {
    for (int i = 0; i < count; i++) {
        int value = dis.readInt();
        System.out.println(Integer.toBinaryString(value));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM