You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何以比特格式将truth array保存至文件?

Hey there! Saving a truth (boolean) array to a file in bit format is all about packing those boolean values into individual bits (instead of whole bytes) to save space. Let's walk through concrete implementations for some common languages:

Python Implementation

Using Standard Libraries (No External Dependencies)

If you want to stick to Python's built-in tools, you can manually pack bits into bytes and write to a binary file:

import struct

def save_truth_array_to_bits(arr, filename):
    # Convert boolean values to 1s and 0s
    bit_sequence = [1 if val else 0 for val in arr]
    # Calculate how many full bytes we need (round up to nearest 8 bits)
    total_bytes = (len(bit_sequence) + 7) // 8
    # Pad the sequence with 0s to make its length a multiple of 8
    padded_bits = bit_sequence + [0] * (total_bytes * 8 - len(bit_sequence))
    
    # Pack each group of 8 bits into a single byte (MSB first)
    byte_buffer = bytearray()
    for i in range(total_bytes):
        current_byte = 0
        for bit_idx in range(8):
            # Shift the bit to its position (leftmost is highest value)
            current_byte |= padded_bits[i*8 + bit_idx] << (7 - bit_idx)
        byte_buffer.append(current_byte)
    
    # Write the byte buffer to file in binary mode
    with open(filename, 'wb') as output_file:
        output_file.write(byte_buffer)

# Example usage
my_truth_array = [True, False, True, True, False, True, False, False, True]
save_truth_array_to_bits(my_truth_array, 'truth_bits.bin')

Using the bitarray Library (More Efficient)

For larger arrays, the third-party bitarray library is optimized for bit-level operations and simplifies the code a lot:

First install it:

pip install bitarray

Then use it like this:

from bitarray import bitarray

def save_truth_array_with_bitarray(arr, filename):
    # Convert the boolean array directly to a bitarray object
    bit_arr = bitarray(arr)
    # Write the bitarray to file in binary mode
    with open(filename, 'wb') as output_file:
        bit_arr.tofile(output_file)

# Example usage
my_truth_array = [True, False, True, True, False, True, False, False, True]
save_truth_array_with_bitarray(my_truth_array, 'truth_bits_bitarray.bin')
C/C++ Implementation

If you're working in a lower-level language, here's how to manually pack bits into bytes and write to a file:

#include <fstream>
#include <vector>
#include <iostream>

void saveTruthArrayToBits(const std::vector<bool>& truth_array, const std::string& file_path) {
    std::ofstream output_file(file_path, std::ios::binary);
    if (!output_file.is_open()) {
        std::cerr << "Failed to open file for writing!" << std::endl;
        return;
    }

    unsigned char current_byte = 0;
    int bit_position = 0;

    for (bool value : truth_array) {
        // Set the corresponding bit in the current byte (MSB first)
        current_byte |= (value ? 1 : 0) << (7 - bit_position);
        bit_position++;

        // When we've filled 8 bits, write the byte to file and reset
        if (bit_position == 8) {
            output_file.write(reinterpret_cast<const char*>(&current_byte), sizeof(current_byte));
            current_byte = 0;
            bit_position = 0;
        }
    }

    // Write any remaining bits (pad with 0s if needed)
    if (bit_position > 0) {
        output_file.write(reinterpret_cast<const char*>(&current_byte), sizeof(current_byte));
    }

    output_file.close();
}

// Example main function
int main() {
    std::vector<bool> my_truth_array = {true, false, true, true, false, true, false, false, true};
    saveTruthArrayToBits(my_truth_array, "truth_bits.bin");
    return 0;
}
Key Things to Remember
  • Bit Order: All examples above use MSB (Most Significant Bit) first (leftmost bit is the highest value). If you need LSB (Least Significant Bit) first, adjust the bit-shifting logic (e.g., use << bit_position instead of << (7 - bit_position)).
  • Reading Back: Make sure your reading code uses the same bit order and padding logic as your writing code to avoid corruption.
  • Efficiency: For very large arrays, specialized libraries (like Python's bitarray) are far more efficient than manual implementations, as they're optimized for memory usage and speed.

内容的提问来源于stack exchange,提问作者lukaszpolowczyk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 06:54:39