

Recall that Python represents all data an object. But we’re learning here, so let’s ignore that hiccup and see some more ridiculous examples.Ĭheck out the article on how to convert hexadecimal values to binary in Python for more examples of how the bin() and hex() functions work in concert (also how they break things sometimes!) Using Bin on Non-Integer Objects If our true goal was to get the hexadecimal value of 42 this would be a silly example-we’d just skip the bin() function altogether as such: hex(42). Consider how the official Python documentation describes its use:Ĭonvert an integer number to a lowercase hexadecimal string prefixed with “0x”. So that isn’t great news but it is expected behavior given the implementation of the hex() function. TypeError: 'str' object cannot be interpreted as an integer For example, let’s try to convert a binary string to a hexadecimal value: # Convert to hexadecimal Python’s bin() function will show you the binary representation of a number but there isn’t a lot you can do with that information explicitly. Six 1's and 0's are used to represent values, the absolute minimum required.Let’s see that in action: # Define a number The simplest use-case is to return the binary value of an integer value-the only valid numerical representation for which the bin() function will accept. The Python bin() function can be used for a range of applications where binary values are of interest. TypeError: 'float' object cannot be interpreted as an integer Basic Use

TL DR – The Python bin() function returns a string representation of an integer’s binary value.

In this article, you will learn the basic usage of the bin() function, some advanced uses, and ways in which one might break things using it. The Python bin() built-in function is a useful tool in translating between languages, domains, and understanding the fundamentals of how low-level data is represented.
