James Peter Mitchell
Little bits of Bytes (and Bits) Published on Wednesday March 26, 2025 2 minutes

Decimal Units

NameUnitTotal Bytes
ExabytesEB1,000,000,000,000,000,000
PetabytesPB1,000,000,000,000,000
TerabytesTB1,000,000,000,000
GigabytesGB1,000,000,000
MegabytesMB1,000,000
KilobytesKB1,000

Binary Units

NameUnitMagnitudeTotal Bytes
ExbibyteEiB2^601,152,921,504,606,846,976
PebibytePiB2^501,125,899,906,842,624
TebibyteTiB2^401,099,511,627,776
GibibyteGiB2^301,073,741,824
MebibyteMiB2^201,048,576
KibibyteKiB2^101,024

Generating Byte String

C++

inline static std::string createBytesString(size_t bytes)
{
    size_t constexpr b10 = size_t(1) << 10;
    size_t constexpr b20 = size_t(1) << 20;
    size_t constexpr b30 = size_t(1) << 30;
    size_t constexpr b40 = size_t(1) << 40;
    size_t constexpr b50 = size_t(1) << 50;
    size_t constexpr b60 = size_t(1) << 60;

    if (bytes < b10) return std::to_string(bytes) + " bytes";
    else if (bytes < b20) return std::to_string(bytes / b10) + " KiB";
    else if (bytes < b30) return std::to_string(bytes / b20) + " MiB";
    else if (bytes < b40) return std::to_string(bytes / b30) + " GiB";
    else if (bytes < b50) return std::to_string(bytes / b40) + " TiB";
    else if (bytes < b60) return std::to_string(bytes / b50) + " PiB";
    return std::to_string(bytes / b60) + " EiB";
}

Python

def create_bytes_string(bytes):
    b10 = 1 << 10  
    b20 = 1 << 20  
    b30 = 1 << 30  
    b40 = 1 << 40  
    b50 = 1 << 50  
    b60 = 1 << 60  
    
    if bytes < b10:
        return f"{bytes} bytes"
    elif bytes < b20:
        return f"{bytes // b10} KiB"
    elif bytes < b30:
        return f"{bytes // b20} MiB"
    elif bytes < b40:
        return f"{bytes // b30} GiB"
    elif bytes < b50:
        return f"{bytes // b40} TiB"
    elif bytes < b60:
        return f"{bytes // b50} PiB"
    return f"{bytes // b60} EiB"