Can I use a binary literal in C or C++?

前端 未结 19 2422
梦如初夏
梦如初夏 2020-11-22 07:40

I need to work with a binary number.

I tried writing:

const x = 00010000;

But it didn\'t work.

I know that I can use an hex

19条回答
  •  一向
    一向 (楼主)
    2020-11-22 07:57

    Based on some other answers, but this one will reject programs with illegal binary literals. Leading zeroes are optional.

    template struct BinaryLiteralDigit;
    
    template<> struct BinaryLiteralDigit {
        static bool const value = true;
    };
    
    template
    struct BinaryLiteral {
        enum {
            value = (BinaryLiteralDigit<(OCT%8 < 2)>::value && BinaryLiteralDigit<(HEX >= 0)>::value
                ? (OCT%8) + (BinaryLiteral::value << 1)
                : -1)
        };
    };
    
    template<>
    struct BinaryLiteral<0, 0> {
        enum {
            value = 0
        };
    };
    
    #define BINARY_LITERAL(n) BinaryLiteral<0##n##LU, 0x##n##LU>::value
    

    Example:

    #define B BINARY_LITERAL
    
    #define COMPILE_ERRORS 0
    
    int main (int argc, char ** argv) {
        int _0s[] = { 0, B(0), B(00), B(000) };
        int _1s[] = { 1, B(1), B(01), B(001) };
        int _2s[] = { 2, B(10), B(010), B(0010) };
        int _3s[] = { 3, B(11), B(011), B(0011) };
        int _4s[] = { 4, B(100), B(0100), B(00100) };
    
        int neg8s[] = { -8, -B(1000) };
    
    #if COMPILE_ERRORS
        int errors[] = { B(-1), B(2), B(9), B(1234567) };
    #endif
    
        return 0;
    }
    

提交回复
热议问题