Python function that turns a number into binary [duplicate] - python

This question already has answers here:
Python int to binary string?
(36 answers)
Closed last year.
I know that in python there are certain functions like bin that turn
decimal numbers into binary numbers. I would like to build one myself. I have tried the following:
def binary(n):
bina = ''
B = []
if n == 0:
bina = '0'
else:
while n>0:
x = 0
while 2**x<n:
x = x+1
B.append(x-1)
n = n-2**(x-1)
The problem is that when I have the exponents with base 2 in the array B I don’t know how to actually read them so that I obtain the actual binary number made of ones and zeroes. How can I make the code above work?
before someone says that my question was already asked, my question is how can I make the code above work,I know that there are other methods to make a binary convertion in python, but I would like to know what's wrong with mine and possibly make my code work.

def make_binary(num):
binary = ''
while num > 0:
binary = str(num % 2) + binary
num = num // 2
return binary
print(make_binary(15))

Related

Printing binary without trailing 0s? [duplicate]

This question already has answers here:
Why does integer division yield a float instead of another integer?
(4 answers)
Closed 4 months ago.
Trying to create a small program that takes in positive integers and converts it into reverse binary.
I've gotten this far:
import math
integer = int(input())
while integer > 0:
x = integer % 2
print(int(math.floor(x)), end='')
integer = integer / 2
The problem with this is that the output would have unnecessary trailing 0s. For example, if the input is 12, the output would be 0011000......
I've tried the int function to remove floats, I also tried floor function to round up(albeit I might've done it wrong).
Could the problem be a lack of sentinel value?
It sounds like you have reversed a binary number like this:
def reverse_bits(n):
res = 0
for i in range(n.bit_length(), -1, -1):
if n & (1 << i):
res += 1 << (n.bit_length() - i)
return res
bin(reverse_bits(12)) # '0b110'
You can bit shift to the right, until there is a 1 in the rightmost bit, to remove trailing zeros:
def remove_trailing_zeros(n):
while not n & 1:
n = n >> 1
return n
All together:
bin(remove_trailing_zeros(reverse_bits(12)))
Out[11]: '0b11'
use // instead of / in division
Here is an alternate approach:
integer = 3
print (bin(integer)[2:][::-1])

How to efficiently determine the binary length of an integer? [duplicate]

This question already has answers here:
Minimum bit length needed for a positive integer in Python
(7 answers)
Closed last year.
I am searching for a fast way to determine the length of an integer in its binary representation using Python. In C++ one may consider uint64_t(log2(x) + 1.0).
Let us take for example the following algorithm that counts numbers having a remainder 17 modulo 24:
def count17mod24(s:int, max_bin_len:int)->int:
x=0
q = queue.Queue()
q.put(s)
while not q.empty():
n = q.get()
if n%3 == 2:
q.put((2*n-1)//3)
if n % 24 == 17:
x += 1
if len(np.binary_repr(n)) < len(np.binary_repr(s))+max_bin_len-1:
q.put(4*n+1)
elif n%3 == 0:
if len(np.binary_repr(n)) < len(np.binary_repr(s))+max_bin_len-1:
q.put(4*n+1)
elif n%3 == 1:
if len(np.binary_repr(n)) < len(np.binary_repr(s))+max_bin_len and n>1:
q.put((4*n-1)//3)
if len(np.binary_repr(n)) < len(np.binary_repr(s))+max_bin_len-1:
q.put(4*n+1)
return x
Those interested in the underlying mathematical problem may want to take a look at this MSE post. I would like to further optimize the algorithm step by step and I believe that the counting of the bits is definitely a possible point of action. Currently I am using np.binary_repr(n) and then measuring its length via len(...).
There are probably many other performance-critical use cases for determining an integers's binary length. I would be very grateful for any ideas to speed this up. Maybe there are some approaches using log2 or similar tricks?
The in-built Python int type has a method bit_length that’s probably the fastest way to do this.
a = 3
print(a.bit_length())
Output: 2

Decimal to Binary number conversion program -- How to make it better or shroter? [duplicate]

This question already has answers here:
Python int to binary string?
(36 answers)
Closed 2 years ago.
I am a beginner in python. I have written a program to convert decimal numbers to binary. It works. But Is there any other way to make it better? Refer to my code. Thanks :)
def decimal_to_binary_converter(dec):
print(f"Decimal: {dec}")
binary = ""
# Using while loop dividing the decimal number by 2 and concatenating the reminder to the string variable "binary" .
# % Operator gets the reminder from the division.
while int(dec) > 0:
binary += str(int(dec)%2)
dec = int(dec) / 2
x = int(len(binary))
rev_binary = ""
# using this while loop reversing the string "binary" and showing the Output.
while x > 0:
rev_binary += str(binary[x-1])
x -= 1
return print(f"Binary: {rev_binary}")
decimal_to_binary_converter(945)
Output:
Decimal: 945
Binary: 1110110001
You can get it in one line
n = int(input())
binaryNo = bin(n).replace("0b","")

Double Slash Assignment division in Python [duplicate]

This question already has answers here:
What exactly does += do?
(17 answers)
Closed 3 years ago.
I am new to Python and found a function that checks to see if an array of arguments can be made equal by only multiplying the number by 2. However, there is some notation that I do not understand.
Function:
def isEqual(a,n): # a is an arrary, n is the length of array
for i in range(0,n):
while a[i]%2==0:
a[i]//=2 # this is the part I do not understand
print(a[i])
if a[i] != a[0]:
return print("False")
# Otherwise, all elements equal, return true
return print("True")
When I step through the function I see that it replaces the a[i] number by a[i]//2, but I do not understand why you would write // equals to number
I understand the // is "floor" division, but not why someone would write a[i]//=2. I would have thought to write it as a[i]=a[i]//2. I can only assume these are the same things, I just never saw it written this way.
Test code:
a = [50, 4, 2]
n = len(a)
isEqual(a, n)
You might have came across operations that also assign value. Think
a += 1 # same as: a = a + 1
This is exactly the same. It integer divides and assigns the value. Probably better understood with proper spacing:
a //= 2 # same as: a = a // 2

Converting a binary string to the equivalent base 10 value in python [duplicate]

This question already has answers here:
Convert base-2 binary number string to int
(10 answers)
Closed 7 years ago.
I want to convert a binary string (user input) to its base 10 equivalent value. I think I am somewhat close but just can't get it. This is what I have come up with so far. I need it to go through each individual number in the binary string and assign its base 10 equivalent value, then add all of those up for the entire base 10 number.
def getBaseTen(myString):
x = myString[0]
needAnswers = len(myString)
n = len(myString)
two = (2^n)
if (needAnswers >= 1):
return (int(x)*int(two))
The built-in int() can do this with an optional argument for the base:
>>> a = '11010'
>>> int(a)
11010
>>> int(a, 2)
26
Something like this: int(x, base=2) Link for more on this.
def getBaseTen(myString):
int(myString, 2)

Categories