Skip to content

IntToBytesBE

Description

Export an integer into big-endian bytes.

Parameters

Name Direction Description
value in Integer to export.
bytes out Destination byte buffer. Must be non-NULL and at least max_len bytes long.
max_len in Maximum bytes to write. Must be non-zero.

Success

Returns the number of bytes written, which is min(IntByteLength(value), max_len). The first byte written holds the most significant 8 bits. value is not modified.

Failure

Returns 0 when value has zero bytes of magnitude. LOG_FATAL when bytes is NULL or max_len is 0.

Usage example (Cross-references)

Usage examples (Cross-references)
            }
    
            (void)IntToBytesBE(value, buffer, byte_len);
            if (!write_char_internal(o, fmt_info->flags, (Zstr)buffer, byte_len)) {
                AllocatorFree(StrAllocator(o), buffer);
    }
    
    u64 IntToBytesBE(const Int *value, u8 *bytes, u64 max_len) {
        ValidateInt(value);
        u8  out[4]  = {0};
        Int value   = IntFromBytesBE(bytes, sizeof(bytes), ALLOCATOR_OF(&alloc));
        u64 written = IntToBytesBE(&value, out, sizeof(out));
        Str text    = IntToHexStr(&value);
    
    bool test_int_to_bytes_be_zero_max_len(void) {
        WriteFmt("Testing IntToBytesBE zero max_len handling\n");
    
        DefaultAllocator alloc = DefaultAllocatorInit();
        u8  byte  = 0;
    
        IntToBytesBE(&value, &byte, 0);
        DefaultAllocatorDeinit(&alloc);
        return false;
    //
    bool test_m21_to_bytes_be_count(void) {
        WriteFmt("Testing IntToBytesBE writes exact byte count\n");
    
        DefaultAllocator alloc = DefaultAllocatorInit();
        Int value     = IntFrom(0x1234, ALLOCATOR_OF(&alloc));
        u8  out[8]    = {0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA};
        u64 written   = IntToBytesBE(&value, out, sizeof(out));
        u8  expect[2] = {0x12, 0x34};
    //
    bool test_m21_to_bytes_be_single(void) {
        WriteFmt("Testing IntToBytesBE single-byte value\n");
    
        DefaultAllocator alloc = DefaultAllocatorInit();
        Int value   = IntFrom(1, ALLOCATOR_OF(&alloc));
        u8  out[4]  = {0xAA, 0xAA, 0xAA, 0xAA};
        u64 written = IntToBytesBE(&value, out, sizeof(out));
    
        bool result = (written == 1);
    // {0x01, 0x02}; the mutant leaves {0x00, 0x00}.
    bool test_fe_603_to_bytes_be_content(void) {
        WriteFmt("Testing IntToBytesBE big-endian content\n");
    
        DefaultAllocator alloc = DefaultAllocatorInit();
        MemSet(buf, 0xAA, sizeof(buf));
    
        u64 written = IntToBytesBE(&value, buf, sizeof(buf));
    
        bool result = written == 2;
Last updated on