Skip to content

Instantly share code, notes, and snippets.

@luxedo
Created October 30, 2019 16:28
Show Gist options
  • Save luxedo/d748ea7e9e0d6941a3bbdfd7b464c9ad to your computer and use it in GitHub Desktop.
Save luxedo/d748ea7e9e0d6941a3bbdfd7b464c9ad to your computer and use it in GitHub Desktop.
Function to convert integer to binary with a fixed length
import sys
import math
MAXIMUM_SIZE = math.ceil(math.log(sys.maxsize, 2))
def int2bin(integer, length=MAXIMUM_SIZE):
"""
Returns the `integer` as an unsigned binary string with a fixed `length` in bits.
Truncates to the `length` in bits to prevent overflow.
"""
max_integer, integer = 2 ** max_size - 1, abs(integer)
return ("0b{0:0={1}b}").format(
integer if integer < max_integer else max_integer,
max_size,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment