Skip to content
BitVecFromInteger

BitVecFromInteger

Description

Build a bitvector from an integer using an explicit allocator.

Parameters

Name Direction Description
value in Integer value to convert.
bits in Number of bits to emit.
alloc in Allocator to bind to the returned bitvector.

Success

Returns initialized bitvector.

Failure

Returns an empty bitvector if allocation fails.

Usage example (Cross-references)

Usage examples (Cross-references)
                bit_len = 4;
    
            *bv = BitVecFromInteger(value, bit_len, BitVecAllocator(bv));
            StrDeinit(&hex_str);
            return StrIterDataAt(&si, StrIterIndex(&si));
                bit_len = 3;
    
            *bv = BitVecFromInteger(value, bit_len, BitVecAllocator(bv));
            StrDeinit(&oct_str);
            return StrIterDataAt(&si, StrIterIndex(&si));
        StrClear(&output);
    
        BitVec bv2 = BitVecFromInteger(0xABCD, 16, alloc_base);
        StrAppendFmt(&output, "{x}", bv2);
        success = success && (ZstrCompare(StrBegin(&output), "0xabcd") == 0);
        StrClear(&output);
    
        BitVec bv3 = BitVecFromInteger(0755, 10, alloc_base);
        StrAppendFmt(&output, "{o}", bv3);
        success = success && (ZstrCompare(StrBegin(&output), "0o755") == 0);
        StrClear(&output);
    
        BitVec bv_zero = BitVecFromInteger(0, 1, alloc_base);
        StrAppendFmt(&output, "{x}", bv_zero);
        success = success && (ZstrCompare(StrBegin(&output), "0x0") == 0);
        DefaultAllocator alloc = DefaultAllocatorInit();
    
        WriteFmt("Testing BitVecFromInteger\n");
    
        // Convert from integer
    
        // Test integer to bitvec with 0
        BitVec bv2 = BitVecFromInteger(0, 8, ALLOCATOR_OF(&alloc)); // 8 bits for zero
        result     = result && (BitVecLen(&bv2) == 8);              // Should be 8 bits
        BitVecDeinit(&bv2);
    
        // Test large integer
        BitVec bv3 = BitVecFromInteger(UINT64_MAX, 64, ALLOCATOR_OF(&alloc)); // 64 bits for max value
        result     = result && (BitVecLen(&bv3) == 64);
        BitVecDeinit(&bv3);
                value    &= mask;
    
                BitVec bv        = BitVecFromInteger(value, bits, ALLOCATOR_OF(&alloc));
                u64    recovered = BitVecToInteger(&bv);
    
        // Test large integer conversion (should cap at 64 bits)
        BitVec large_bv = BitVecFromInteger(0xFFFFFFFFFFFFFFFF, 64, ALLOCATOR_OF(&alloc));
        result          = result && (BitVecLen(&large_bv) == 64);
        // Test cross-format validation
        BitVec bv1 = BitVecFromStr("11010110", ALLOCATOR_OF(&alloc));
        BitVec bv2 = BitVecFromInteger(0xD6, 8, ALLOCATOR_OF(&alloc)); // Assuming MSB-first: 11010110 = 0xD6
        BitVec bv3 = BitVecFromBytes((u8[]) {0xD6}, 8, ALLOCATOR_OF(&alloc));
Last updated on