Search code examples
pythonbinarybinary-databuilt-in

Is there a Python built-in method that checks if an integer is in binary format or not?


I know the logic behind implementing my own but there a built-in Python function that takes an integer and returns True if it is written in binary form?

For example, is_binary(0b1010) would return True but is_binary(12) would return False.


Solution

  • No, since 0b1010 is converted to the same representation as 10 by the 'compiler', which of course happens long before it is being passed to the function.

    We can confirm this by investigating the produced code.

    import dis
    
    def binary():
        a = 0b1010
    
    def base_10():
        a = 10
    
    dis.dis(binary)
    print()
    dis.dis(base_10)
    

    Outputs

     17           0 LOAD_CONST               1 (10)   # <-- Same represntation here
                  2 STORE_FAST               0 (a)
                  4 LOAD_CONST               0 (None)
                  6 RETURN_VALUE
    
     20           0 LOAD_CONST               1 (10)   # <-- as here
                  2 STORE_FAST               0 (a)
                  4 LOAD_CONST               0 (None)
                  6 RETURN_VALUE
    

    If it is that important for you, you will have to implement some sort of AST parser which I assume will be able to grab the binary literal before it is converted.