Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C++11

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

Rate me:
Please Sign up or sign in to vote.
4.98/5 (30 votes)
31 Aug 2012CPOL7 min read 52K   379   41  
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)));
}


unsigned long long operator"" _b(const char* str) 
{             
    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)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions