BitVecToBytes

Table of Contents

BitVecToBytes

Description

Export bitvector to byte array. Copies the internal bit representation to the provided byte array.

Parameters

NameDirectionDescription
bvinBitvector to export
bytesoutByte array to write to (must be large enough)
max_leninMaximum bytes to write

Usage example (from documentation)

  u8 buffer[16];
  u64 written = BitVecToBytes(&flags, buffer, 16);

Usage example (Cross-references)

    }
    
    u64 BitVecToBytes(BitVec *bv, u8 *bytes, u64 max_len) {
    ValidateBitVec(bv);
    if (!bytes) {
    // Test BitVecToBytes function
    bool test_bitvec_to_bytes(void) {
    printf("Testing BitVecToBytes\n");
    
    BitVec bv = BitVecInit();
    
    u8  bytes[2];           // Buffer for byte output
    u64 byte_count = BitVecToBytes(&bv, bytes, sizeof(bytes));
    
    // Check result
    // Test empty bitvec to bytes
    u8  bytes[1] = {0};
    u64 written  = BitVecToBytes(&bv, bytes, 1);
    result       = result && (written == 0); // Empty bitvec should write 0 bytes
    BitVec bv             = BitVecFromBytes(&test_bytes[i], 8);
    u8     recovered_byte = 0;
    u64    written        = BitVecToBytes(&bv, &recovered_byte, 1);
    
    result = result && (written == 1);
    
    u8  empty_bytes[1] = {0xFF};
    u64 empty_written  = BitVecToBytes(&empty, empty_bytes, 1);
    result             = result && (empty_written == 0);
    result             = result && (empty_bytes[0] == 0xFF); // Should be unchanged
    // Test byte conversion
    u8  bytes[8] = {0};
    u64 written  = BitVecToBytes(&bv, bytes, 8);
    result       = result && (written == test_cases[i].byte_count);
    // Test byte conversion
    u8  large_bytes[125]; // 1000 bits = 125 bytes
    u64 written = BitVecToBytes(&large_bv, large_bytes, 125);
    result      = result && (written == 125);
    // Test with insufficient buffer size
    u8  small_buffer[1];
    u64 written = BitVecToBytes(&bv, small_buffer, 0); // 0 buffer size
    (void)written;                                     // Suppress unused variable warning

Share :

Related Posts

BitVecIsSorted

BitVecIsSorted Description Check if bits in bitvector are in sorted order. Useful for certain algorithms and data structures.

Read More

BitVecToStr

BitVecToStr Description Convert bitvector to string representation. Each bit becomes ‘1’ or ‘0’ character. Caller must free the returned string.

Read More

BitVecWeightCompare

BitVecWeightCompare Description Compare two bitvectors by their Hamming weights (number of 1s).

Read More