I've got an algorithm that does this already, but the code is ugly and slow. I assume that there's a built-in or some function in the libs that give faster and more precise results.
What I want it where I can give a final number of bits, a string, list or deque (anything that can be cast to a string in the end).
func(totalBits, binaryInStringOrListForm) -> String or List with leading zeroes
The code I've already got is below:
val = deque(["1", "0"])
while len(val) < 8:
val.appendleft("0")
By the way, deque is a type of object from collections that allows you to leftappend
wherein you can add an item to the beginning of the list without having to shift everything over by one.
There are old answers to this but they're all Python 2 and the whole formatting thing has changed significantly.
EDIT: I think that this question is not a duplicate of the one linked as I was actually after leading zeroes as @Martijn Pieters has made me aware.
EDIT: Ok, it IS a duplicate of that one it seems. Sorry about the dupe.
LAST EDIT I SWEAR: I just noticed something. I keep getting values like 000b0110 when trying to make it one-byte long. This is opposed to 00000110 that I wanted. I'm just adding this so that if anyone else in the future looks up this question they'll find the correct thing. So all I've done is ignore the first two character of the string by using:
val = val[2::].rjust(8, '0')
I'm getting this because I'm turning a number INTO a binary number with "bin" which returns a string that has the "0b" (declaring it as binary) at the beginning.