【问题标题】:How to convert boolean array to binary and vice versa in Java?如何在Java中将布尔数组转换为二进制,反之亦然?
【发布时间】:2012-03-10 02:35:55
【问题描述】:

在 Java 中将布尔数组输出到(和输入)文件的最有效方法是什么?我打算使用一个字符串,每个字符要么是 't' 要么是 'f',然后我想,为什么不减少八倍的空间呢?

注意

我实际上不知道哪个答案是更好的方法,我只是选择了彼得的方法,因为我理解它。感谢两位回答者!

【问题讨论】:

  • 一般结果是将布尔数组转换为字节数组(其中 1 位是一个布尔值)并将其输出到文件。那么问题就变成了如何有效地做这样的事情。您只需将位存储在文件中,还是需要特定的文件格式?
  • 嗨@owlstead,感谢您的回复。不,没有特定的文件格式。该文件将首先指示布尔数组的大小,然后读取算法将使用它来了解文件的后续字节数代表该数组。
  • 有趣,听起来确实像一种文件格式。布尔值的最大大小(如果有)是多少?
  • @owlstead 我以为您的意思是已经建立的文件格式。数组的最大大小为 10K(一万个布尔值)

标签: java file-io binary encode


【解决方案1】:

假设你有一个 boolean[]

boolean[] ar = {true,false,false,true,false,true,true,true,false,true,false,false,false,true,tr‌​ue};

你想把它写到磁盘上,你并不关心它是如何在内存中实现的。

public static void main(String... args) throws IOException {
    boolean[] ar = {true, false, false, true, false, true, true, true, false, true, false, false, false, true, true};

    FileOutputStream out = new FileOutputStream("test.dat");
    writeBooleans(out, ar);
    out.close();

    FileInputStream in = new FileInputStream("test.dat");
    boolean[] ar2 = new boolean[ar.length]; 
    readBooleans(in, ar2);
    in.close();

    System.out.println(Arrays.toString(ar));
    System.out.println(Arrays.toString(ar2));
    System.out.println("The file size was "+new File("test.dat").length()+" bytes.");
}

private static void writeBooleans(OutputStream out, boolean[] ar) throws IOException {
    for (int i = 0; i < ar.length; i += 8) {
        int b = 0;
        for (int j = Math.min(i + 7, ar.length-1); j >= i; j--) {
            b = (b << 1) | (ar[j] ? 1 : 0);
        }
        out.write(b);
    }
}

private static void readBooleans(InputStream in, boolean[] ar) throws IOException {
    for (int i = 0; i < ar.length; i += 8) {
        int b = in.read();
        if (b < 0) throw new EOFException();
        for (int j = i; j < i + 8 && j < ar.length; j++) {
            ar[j] = (b & 1) != 0;
            b >>>= 1;
        }
    }
}

打印

[true, false, false, true, false, true, true, true, false, true, false, false, false, true, true]
[true, false, false, true, false, true, true, true, false, true, false, false, false, true, true]
The file size was 2 bytes.

但是如果我看看文件实际上有多大

$ ls -l test.dat
-rw-rw-r-- 1 peter peter 2 2012-02-19 14:04 test.dat
$ du -h test.dat 
4.0K    test.dat

它说长度是2字节,但实际使用的磁盘空间是4 KB。

注意:大约 1 分钟的时间相当于 80 MB 的 SSD(昂贵的磁盘,更多用于 HDD)因此,如果您认为使用它不会节省至少 80 MB,您可以浪费你的时间。 ;)


您可以使用 BitSet,它可以减少 16 倍的空间,因为每个字符都是 16 位的。

【讨论】:

  • BitSet 不是文件,请在回答前阅读问题。
  • @Peter 太棒了!你能告诉我怎么做吗?在文件中存储和检索boolean[] ar = {true,false,false,true,false,true,true,true,false,true,false,false,false,true,true}; 的最佳方式是什么?
  • 每个字符都是16位?不在磁盘上,它不在:完全取决于编码——比如说,UTF-8 对于t 或f 只需要8 位。我仍然同意位掩码的概念是提高空间效率的方法:长度 = O(n) + 1,其中 n 是布尔数组的长度。
  • @owlstead 它并没有说它必须成为一个文件,它说来自一个暗示它是别的东西的文件。请在尝试纠正某人之前阅读问题。 ;)
  • 是的,对 :) 我个人讨厌 BitSet,因为它不提供任何转换方法。真的和 EnumSet 一样。我已经为这两个函数编写了一些库函数,我应该将它们发送给 Joshua Bloch。
【解决方案2】:

全新打造,专为您打造。我将把BooleanInputStream 留作练习。请注意,第一位现在是文件中最右边的 (MSB) 位(在示例中删除 Byte.SIZE - 1 - 以获得其他字节顺序,无论您喜欢什么)。只需使用例如DataOutputStream 先将事物的大小写入文件。 10K 应该是一个整数。

请注意,存储 10K 元素的布尔数组在内存方面效率非常低,您当然应该为此使用 BitSet(最后,需要 BitSet 的人)!

public final class BooleanOutputStream extends FilterOutputStream {

    private int bitIndex;
    private byte buffer;

    public BooleanOutputStream(final OutputStream out) {
        super(out);
    }

    public void writeBoolean(final boolean value) throws IOException {
        buffer ^= (value ? 1 : 0) << (Byte.SIZE - 1 - bitIndex++);
        if (bitIndex == Byte.SIZE) {
            write(buffer & 0xFF);
            buffer = 0;
            bitIndex = 0;
        }
    }

    /**
     * This is an encoder and does therefore not close the underlying stream.
     * Please close underlying stream separately.
     */
    public void close() throws IOException {
        if (bitIndex != 0) {
            out.write(buffer);
            buffer = 0;
            bitIndex = 0;
        }
    }
}

public class BooleanInputStream extends FilterInputStream {

    private int bitIndex;
    private byte buffer;

    public BooleanInputStream(final InputStream in) {
        super(in);
    }

    public boolean readBoolean() throws IOException {
        if (bitIndex == 0) {
            int b = read();
            if (b == -1) {
                throw new EOFException();
            }
            buffer = (byte) b;
        }

        boolean value = (buffer & (1 << (Byte.SIZE - 1 - bitIndex++))) != 0;
        if (bitIndex == Byte.SIZE) {
            bitIndex = 0;
        }
        return value;
    }

    /**
     * This is a decoder and therefore does not close the underlying stream.
     * Please close underlying stream separately.
     */    
    public void close() throws IOException {
        buffer = 0;
        bitIndex = 0;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多