// BitsExample.cpp 
// Rangarajan Krishnamoorthy, Nov 1, 2026
//

#include <bit>
#include <cstdint>
#include <iostream>

void example1()
{
    // How many bits do we need to represent the given unsigned integer?
    std::uint32_t max_val{ 1000 };
    std::cout << std::bit_width(max_val) << std::endl;
    std::uint32_t max_val2{ 255 }, max_val3{ 256 };
    std::cout << std::bit_width(max_val2) << ", " << std::bit_width(max_val3) << std::endl;

    // How many bits are set to 1?
    std::cout << std::popcount(max_val) << ", " << std::popcount(max_val2) << ", " << std::popcount(max_val3);
}

void example2()
{
    float fval = 5.0f;
    // What is the corresponding bit representation?
    std::uint32_t ival = std::bit_cast<int>(fval);
    std::cout << "Float = " << std::hex << fval << ", Bit cast = " << ival << std::endl;

    // Is the value a power of 2?
    std::cout << std::boolalpha << std::has_single_bit(3u) << std::endl;
    std::cout << std::boolalpha << std::has_single_bit(64u) << std::endl;
}

void example3()
{
    // Round up to the nearest power of 2
    std::cout << std::bit_ceil(5u) << ", " << std::bit_ceil(8u) << ", " << std::bit_ceil(0u) << std::endl;

    // Round down to the nearest power of 2
    std::cout << std::bit_floor(10u) << ", " << std::bit_floor(0u) << std::endl;

    // Reverse the bytes
    std::cout << std::hex << std::byteswap(0x12345678u) << std::endl;
}

void example4()
{
    // Is this platform little-endian or big-endian?
    if (std::endian::native == std::endian::little)
        std::cout << "Little-endian\n";
    else if (std::endian::native == std::endian::big)
        std::cout << "Big-endian\n";
    else
        std::cout << "Mixed-endian\n";
}

int main()
{
//    example1();
//    example2();
//    example3();
    example4();
}

