Skip to content

Instantly share code, notes, and snippets.

@K4zuki
Created October 13, 2025 15:55
Show Gist options
  • Select an option

  • Save K4zuki/1ddc98818eeb526ea21ab71da91c5187 to your computer and use it in GitHub Desktop.

Select an option

Save K4zuki/1ddc98818eeb526ea21ab71da91c5187 to your computer and use it in GitHub Desktop.
`a_to_bin_str.py` (仮)
from math import ceil
def a_to_bin_str(b: int):
""" integer to binary string with 0b and 4-digits separation by '_'
>>> a_to_bin_str(123)
>>> '0b0111_1011'
:param int b:
:return str: formatted string
"""
header_length = 2 # length of '0b'
no_0b = len(bin(b)) - header_length
underscores = no_0b // 4 # number of '_'
ceil_length = 4 * ceil(no_0b / 4) # round up to 4N digits
format_str = "{{:#0{}_b}}".format(underscores + ceil_length + header_length)
return format_str.format(b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment