C++ binary constant/literal

后端 未结 7 2157
-上瘾入骨i
-上瘾入骨i 2020-12-14 21:09

I\'m using a well known template to allow binary constants

template< unsigned long long N >
struct binary
{
  enum { value = (N % 10) + 2 * binary<          


        
7条回答
  •  星月不相逢
    2020-12-14 21:37

    The approaches I've always used, though not as elegant as yours:

    1/ Just use hex. After a while, you just get to know which hex digits represent which bit patterns.

    2/ Use constants and OR or ADD them. For example (may need qualifiers on the bit patterns to make them unsigned or long):

    #define b0  0x00000001
    #define b1  0x00000002
    : : :
    #define b31 0x80000000
    
    unsigned long x = b2 | b7
    

    3/ If performance isn't critical and readability is important, you can just do it at runtime with a function such as "x = fromBin("101011011");".

    4/ As a sneaky solution, you could write a pre-pre-processor that goes through your *.cppme files and creates the *.cpp ones by replacing all "0b101011011"-type strings with their equivalent "0x15b" strings). I wouldn't do this lightly since there's all sorts of tricky combinations of syntax you may have to worry about. But it would allow you to write your string as you want to without having to worry about the vagaries of the compiler, and you could limit the syntax trickiness by careful coding.

    Of course, the next step after that would be patching GCC to recognize "0b" constants but that may be an overkill :-)

提交回复
热议问题