Skip to content

Instantly share code, notes, and snippets.

@dooglus
Created November 16, 2014 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dooglus/863daab1a8c6431b6338 to your computer and use it in GitHub Desktop.
Save dooglus/863daab1a8c6431b6338 to your computer and use it in GitHub Desktop.
#include <boost/spirit/include/classic_core.hpp>
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdint.h>
using namespace std;
using namespace boost::spirit::classic;
struct count_satoshis
{
count_satoshis(uint64_t& val_) : val(val_) {}
void operator()(const char* a, const char* b) const
{
val = 0;
int i, c;
for (i = 0; i < 8; i++) {
if (a + i < b)
c = a[i] - '0';
else
c = 0;
val *= 10;
val += c;
}
}
uint64_t& val;
};
uint_parser<uint64_t, 10, 1, -1> uint_left;
uint_parser<uint64_t, 10, 1, 1> digit;
bool parse_number(char const* str, int64_t& n)
{
bool is_negative = false;
uint64_t left = 0, right = 0;
count_satoshis save_right(right);
rule<>
left_ = uint_left[assign_a(left)],
right_ = (+digit)[count_satoshis(right)],
number_ = !sign_p[assign_a(is_negative)] >> ((!left_) >> ch_p('.') >> right_
| left_ >> !ch_p('.'));
bool ret = parse(str, number_).full;
if (ret)
n = (is_negative ? -1 : 1) * (left * 100000000 + right);
return ret;
}
int main()
{
string str;
int64_t n;
while (getline(cin, str))
if (parse_number(str.c_str(), n))
cout << str << " --> " << n << endl;
else
cout << "failed" << endl;
return 0;
}
@dooglus
Copy link
Author

dooglus commented Nov 16, 2014

Some inputs and outputs:

$ ./a.out
> 123.4567890123
123.4567890123 --> 12345678901

> 123456789.12345678
123456789.12345678 --> 12345678912345678

> 123456789.12345677
123456789.12345677 --> 12345678912345677

> 123456789.12345676
123456789.12345676 --> 12345678912345676

> -1.1
-1.1 --> -110000000

> -0.1
-0.1 --> -10000000

> -.1
-.1 --> -10000000

> -1.
-1. --> -100000000

> 1.1
1.1 --> 110000000

> 0.1
0.1 --> 10000000

> .1
.1 --> 10000000

> 1.
1. --> 100000000

> 0.
0. --> 0

> .0
.0 --> 0

> 0.0
0.0 --> 0

> .
failed

> 12..34
failed

> 1234
1234 --> 123400000000

> 1234567890
1234567890 --> 123456789000000000

> 12345678901
12345678901 --> 1234567890100000000

> 123456789012
123456789012 --> -6101065172509551616

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment