Click here to Skip to main content
Click here to Skip to main content
 
Add your own
alternative version
Go to top

Application of C++11 User-Defined Literals to Handling Scientific Quantities, Number Representation and String Manipulation

, 31 Aug 2012
keywords: user-defined literals , templates, constant expressions, recursive functions
#include <iostream>
#include <iomanip>
#include <string>

constexpr unsigned long long Scale(unsigned long long x, const char* s)
{
    return (!*s ? x : Scale(10*x + ((unsigned long long)*s)-((unsigned long long)'0'), s+1));
}

constexpr unsigned long long ToScaledBinary(unsigned long long x, unsigned long long scale, const char* s)
{
    return (!*s 
            ? x 
            : ( *s == 'e' || *s == 'E' 
                ? (x << Scale(0,s+1))
                : ToScaledBinary(x + x + (*s =='1'? 1 : 0), scale,  s+1)));
}

template<char...chars>
unsigned long long operator"" _b() 
{         
    constexpr static char str[] = {chars..., '\0'};
    return ToScaledBinary(0,0,str);
}

int main()
{
    std::cout << std::hex << "0x" << 1111111111_b << std::endl;    
    std::cout << std::hex << "0x" << 1111111111e16_b << std::endl;
    std::cout << std::hex << "0x" << 1e32_b << std::endl;    
    std::cout << std::dec << 1e32_b << std::endl;    
    std::cout << std::dec << 1011e16_b << std::endl;    
    return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mikhail Semenov
Software Developer (Senior)
United Kingdom United Kingdom
No Biography provided

| Advertise | Privacy | Mobile
Web01 | 2.8.140926.1 | Last Updated 1 Sep 2012
Article Copyright 2012 by Mikhail Semenov
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid