Click here to Skip to main content
Click here to Skip to main content
 

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

By , 31 Aug 2012
 
#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 use 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)

About the Author

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

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