Python bin()

Python bin() function takes an integer as input and returns its binary equivalent as a string, prefixed with "0b" to indicate a binary value. This function helps understand how numbers are represented in base-2 format, which is fundamental in computer science.
Table of Contents

Understanding Python bin() Function

Python bin() is a built-in function that converts an integer into its binary string representation. A binary string is a sequence of 0s and 1s representing the number in base-2 format. The bin() function prefixes the binary string with “0b” to indicate that it’s a binary representation. It’s a helpful function for visualizing or working with the binary form of an integer. When you use the bin() function, it always returns a string, and it only works with integers as its input.

Syntax of Python bin()

binary_string = bin(integer)

Explanation

  • binary_string: Variable will store the binary string representation of the integer.
  • bin(): Built-in function that performs the integer-to-binary conversion.
  • integer: Integer you want to convert to its binary form. It is used as input for the bin() function.

Example of Python bin()

number = 10
binary_representation = bin(number)
print(binary_representation)

Explanation

  • number = 10: Assigns the integer value 10 to the variable number.
  • binary_representation = bin(number): The bin() function converts number to its binary string and stores it in binary_representation.
  • print(binary_representation): Prints the value of binary_representation, which is “0b1010”.

Output

0b1010


Python bin() with Negative Number

When you use Python bin() with a negative integer, it returns a binary string that starts with “-0b” followed by the binary representation of the absolute value of the number. It does not use two’s complement representation, commonly used for storing negative numbers in computers. Instead, it simply adds a negative sign in front of the binary representation of the positive version of the number.

Example

negative_number = -5
binary_representation = bin(negative_number)
print(binary_representation)

Explanation

  • negative_number = -5: Assigns the integer value -5 to the variable negative_number.
  • binary_representation = bin(negative_number): The bin() function converts negative_number to its binary string and stores it in binary_representation.
  • print(binary_representation): Prints the value of binary_representation, which is “-0b101”.

Output

-0b101


Python bin() with Large Number

Python bin() can handle large integers without any issues. Python supports arbitrarily large integers, so the bin() function can convert them to their binary string representations regardless of their size. The resulting binary string will be longer for larger numbers. There’s no practical limit to the integer size you can use with bin().

Example

large_number = 1234567890
binary_representation = bin(large_number)
print(binary_representation)

Explanation

  • large_number = 1234567890: Assigns a large integer value to the variable large_number.
  • binary_representation = bin(large_number): The bin() function converts large_number to its binary string and stores it in binary_representation.
  • print(binary_representation): Prints the value of binary_representation, which is “0b1001001100101100000001011010010”.

Output

0b1001001100101100000001011010010


Python bin() with Zero

Using Python bin() with the integer 0 returns the string “0b0”. This binary representation of zero is prefixed with “0b” to indicate a binary value. It’s a straightforward case where the input is the additive identity, and the output is its corresponding binary representation.

Example

zero = 0
binary_representation = bin(zero)
print(binary_representation)

Explanation

  • zero = 0: Assigns the integer value 0 to the variable zero.
  • binary_representation = bin(zero): The bin() function converts zero to its binary string and stores it in binary_representation.
  • print(binary_representation): Prints the value of binary_representation, which is “0b0”.

Output

0b0


Python bin() with Non-Integer Class

Python bin() function is designed to work specifically with integers. If you try to use it directly with a non-integer object, like a string, a float, or an object of a custom class, it will raise a TypeError. This is because bin() doesn’t know how to convert these types into binary representations. To make bin() work with non-integer objects, you must first define how they should be converted to an integer.

Example

try:
    float_number = 3.14
    binary_representation = bin(float_number)
    print(binary_representation)
except TypeError as e:
    print(f"TypeError: {e}")

Explanation

  • float_number = 3.14: Assigns a float value to the variable float_number.
  • binary_representation = bin(float_number): The bin() function is called with a float which raises a TypeError.
  • print(binary_representation): This line will not be reached because of the error.
  • except TypeError as e:: This line catches the TypeError.
  • print(f"TypeError: {e}"): Prints the error message.

Output

TypeError: ‘float’ object cannot be interpreted as an integer


Python bin() with __index__() for Non-Integer Class

To make Python bin() work with a custom class, you need to define the special __index__() method in your class. This method should return an integer representation of your object. When bin() encounters an object of your class, it will call the __index__() method to get the integer equivalent and then convert that integer to its binary string. This lets you define how your custom objects should be treated when passed to bin().

Syntax

class MyClass:
    def __index__(self):
        return integer_representation

binary_string = bin(MyClass_object)

Explanation

  • class MyClass:: Defines a custom class named MyClass.
  • def __index__(self):: Defines the special method __index__ within the class.
  • return integer_representation: Returns an integer that represents the object. integer_representation should be replaced by an integer value.
  • binary_string = bin(MyClass_object): The bin() function will use the __index__ method to convert the object to a binary string.
  • MyClass_object: Object of MyClass.

Example

class MyNumber:
    def __init__(self, value):
        self.value = value

    def __index__(self):
        return self.value

my_object = MyNumber(42)
binary_representation = bin(my_object)
print(binary_representation)

Explanation

  • class MyNumber:: Defines a custom class named MyNumber.
  • def __init__(self, value):: This is the constructor for the class.
  • self.value = value: Initializes the value attribute of the object.
  • def __index__(self):: Defines the __index__ method, which is called by bin().
  • return self.value: Returns the integer value of the object.
  • my_object = MyNumber(42): Creates an instance of MyNumber with a value of 42.
  • binary_representation = bin(my_object): The bin() function uses __index__() to convert my_object to a binary string.
  • print(binary_representation): Prints the value of binary_representation, which is “0b101010”.

Output

0b101010


Conclusion

Python bin() function is a specialized tool for converting integers into binary string representations. While it works seamlessly with integers, including negative and large numbers, it requires special handling for non-integer types through the __index__() method. Understanding the behavior and limitations of Python bin is crucial for effectively working with binary representations in Python. Using the bin() function, you can only get the binary representation of an integer.


Also Read

Python ascii()

Python bool()


Python Reference

python bin()

Table of Contents