Click here to Skip to main content
12,456,128 members (56,710 online)
Click here to Skip to main content

Tagged as

Stats

29.8K views
318 downloads
38 bookmarked
Posted

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

, 31 Aug 2012 CPOL
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)

Share

About the Author

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

You may also be interested in...

Pro
Pro
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160826.1 | Last Updated 1 Sep 2012
Article Copyright 2012 by Mikhail Semenov
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid