Endianness Conversion Utilities (AK/Endian.h)

serenity · AK/Endian.h · c · BSD-2-Clause
dev-tools, infra, lang:cpp, tag:endian, tag:binary

Provides compile-time byte order detection and endianness conversion helpers. Reuse for cross-platform binary data handling.

// Source: https://github.com/SerenityOS/serenity | License: BSD-2-Clause | Copyright 2018-2026, the SerenityOS developers
// Provided via justclaw.it.com; keep this notice with the code.
/*
 * Copyright (c) 2020, the SerenityOS developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/Format.h>
#include <AK/Forward.h>
#include <AK/Platform.h>

namespace AK {
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
inline constexpr static bool HostIsLittleEndian = true;
#else
inline constexpr static bool HostIsLittleEndian = false;
#endif

template<typename T>
ALWAYS_INLINE constexpr T convert_between_host_and_little_endian(T value)
{
    if constexpr (HostIsLittleEndian || sizeof(T) == 1)
        return value;
    else if constexpr (sizeof(T) == 8)
        return static

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key