Created
October 30, 2019 16:28
-
-
Save luxedo/d748ea7e9e0d6941a3bbdfd7b464c9ad to your computer and use it in GitHub Desktop.
Function to convert integer to binary with a fixed length
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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