How can I define custom literals?

254 views Asked by At

I am converting some source code from one scripting language (PAWN) to a programming language (C++) on Windows.

The source code has millions of binary literals all over the place in the form of:

data[] = 
{
    0b11111111111011111110110111111110, 0b00000000001111111111111111111111,
    0b00000000000000000000000000000000, 0b00000000000000000000000000000000,
    0b00000000000000000000000000000000, 0b00000000000000000000000000000000,
    0b00000000000000000000000000000000, 0b00000000000000000000000000000000,
    ///some million lines later...
    0b00000000000000000000000000000000, 0b11111111111111111111111110000000,
    0b11100001001111111111111111111111, 0b11110111111111111111111111111111,
    0b11111111111111111111111111111111, 0b11111111111111111111111111111111,

To my unfortunate luck Visual Studio 2013 doesn't support the user defined literals standard.

Is there any wya to achieve this somehow? 010101_b or something with C++, maybe with a little addition of boost?

2

There are 2 answers

0
Columbo On BEST ANSWER

I strongly advise you to transform the source code with a script.

Anyway, if you're interested in Boost.PP:

#define FROM_BINARY(s, data, elem) sum(#elem+2)

constexpr auto sum(char const* str, std::uintmax_t val = 0) -> decltype(val)
{
    return !*str? val : sum(str+1, (val << 1) + *str - '0');
}

unsigned data[]
{
    BOOST_PP_TUPLE_REM_CTOR(BOOST_PP_SEQ_TO_TUPLE(
        BOOST_PP_SEQ_TRANSFORM(FROM_BINARY, , 
            BOOST_PP_VARIADIC_TO_SEQ(
    0b11111111111011111110110111111110, 0b00000000001111111111111111111111,
    0b00000000000000000000000000000000, 0b00000000000000000000000000000000,
    0b00000000000000000000000000000000, 0b00000000000000000000000000000000,
    0b00000000000000000000000000000000, 0b00000000000000000000000000000000,
    ///some million lines later...
    0b00000000000000000000000000000000, 0b11111111111111111111111110000000,
    0b11100001001111111111111111111111, 0b11110111111111111111111111111111,
    0b11111111111111111111111111111111, 0b11111111111111111111111111111111))))
};

Note that this could horribly slow down compile time. So, again, try to transform the source dode once instead.

0
Thomas Matthews On

I suggest writing a simple, small, console program that converts the binary literals into hexadecimal literals.

Here's the process I would use:

  1. Copy the file.
  2. Using a text editor, remove everything before the first literal.
  3. Remove everything after the last literal.
  4. Save.
  5. Replace the ", " with a newline.
  6. Save.

You now have a text file with the binary literals, one per line.

Write a program to read in the file, convert to hexadecimal literals and output.

Then edit this file by pasting in all the missing stuff.