Sling Academy
Home/Python/Python: 2 Ways to Convert an Integer to Binary

Python: 2 Ways to Convert an Integer to Binary

Last updated: June 03, 2023

This concise article shows you two approaches to converting an integer to binary in Python.

Using the bin() function

The bin() function takes an integer as input and returns a string representing the binary value. That resulting string starts with the 0b prefix. You can easily remove it by using string slicing as needed.

Example:

number = 1985

# Convert the number to binary
binary = bin(number)

# Remove the '0b' prefix
binary = binary[2:]

print(binary)

Output:

11111000001

Using the format() function with binary specifier

The format() function can be used to turn an integer into its binary representations. Just pass the number as the first argument and specify the format specifier b to indicate binary.

Code example:

# Possitive integer to binary
possitive_int = 2023
possitive_binary = format(possitive_int, 'b')
print(possitive_binary)

# Negative integer to binary
negative_int = -2023
negative_binary = format(negative_int, 'b')
print(negative_binary)

Output:

11111100111
-11111100111

Done!

Next Article: Python: How to Convert a Float to Binary (2 Ways)

Previous Article: How to Convert a Number to a Hex String in Python

Series: Python – Numbers & Math Tutorials

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots