Skip to content
IntTryFromBinary

IntTryFromBinary

Description

Parse a binary string into an integer. Accepts an optional 0b or 0B prefix; underscore separators between digits are silently skipped.

Parameters

Name Direction Description
out in,out Int to overwrite with the parsed value. Must already be a valid initialised Int; its allocator is reused for the parsed result.
binary in Null-terminated binary string, optionally prefixed with 0b / 0B.

Success

Returns true. *out is deinitialised and replaced with the normalised parsed value.

Failure

Returns false on a non-binary character, an empty digit run, or an allocation failure during accumulation. *out retains its pre-call value.

Usage example (Cross-references)

Usage examples (Cross-references)
        Int  parsed = IntFromBinary("10a1", ALLOCATOR_OF(&alloc));
        Int  value  = IntInit(ALLOCATOR_OF(&alloc));
        bool result = !IntTryFromBinary(&value, "10a1");
    
        result = result && IntIsZero(&parsed);
    
    bool test_int_try_from_binary_null(void) {
        WriteFmt("Testing IntTryFromBinary NULL handling\n");
    
        DefaultAllocator alloc = DefaultAllocatorInit();
    
        Int value = IntInit(ALLOCATOR_OF(&alloc));
        IntTryFromBinary(&value, (Zstr)NULL);
        IntDeinit(&value);
        DefaultAllocatorDeinit(&alloc);
    // ---------------------------------------------------------------------------
    bool test_m24_binary_reject_nonbinary_prefix(void) {
        WriteFmt("Testing IntTryFromBinary rejects \"0c1\"\n");
    
        DefaultAllocator alloc = DefaultAllocatorInit();
    
        Int  out    = IntInit(&alloc.base);
        bool parsed = IntTryFromBinary(&out, "0c1");
    
        bool fail = parsed; // real code must reject this string.
    // prefix branch is still taken for real 'b' prefixes.
    bool test_m24_binary_accept_real_prefix(void) {
        WriteFmt("Testing IntTryFromBinary accepts \"0b101\" -> 5\n");
    
        DefaultAllocator alloc = DefaultAllocatorInit();
    
        Int  out    = IntInit(&alloc.base);
        bool parsed = IntTryFromBinary(&out, "0b101");
    
        bool fail = !parsed;
Last updated on