Can someone please explain these lines of Python program for me:
b =input("What number would you like to convert into Binary? ")
convert = lambda d: bin(int(d)) [2:]
print(b + " is " + convert(b) + " in Binary")
And also these lines of code:
b = input("What Binary number would you like to convert into Decimal? ")
convert= lambda b: str(int(b, 2))
print(b + " is " + convert(b) + " in Decimal")
The lambda expression is a way of defining a short function, e.g.
f = lambda x: x**2 # e.g. f(2) == 4
is equivalent to
def f(x):
return x**2
int(d) converts d into an integer. bin(...) takes that integer and converts it into a binary string, which looks like:
bin(int(3)) == '0b11'
Note that the first two characters, 0b, are not really part of the number, so we use slice notation [2:] to return everything from index 2 onwards:
'0b11'[2:] == '11'
Finally, the optional second argument to int sets the base that should be used for converting the argument; in this case, base 2 (binary):
int('11', 2) == 3
You can use this for other bases, too, e.g. 16 (hexadecimal):
int('11', 16) == 17
Decimal to binary:
bin(124)
This will give the value '0b1111100'
Binary to decimal:
int('0b1111100', 2)
This will give the value 124
decimal to binary conversion
if n=5
bin=lambda x : format(x,'b')
print(bin(n))
First statement will make bin a function which will take a argument and convert it into binary, format is used to convert int to binary and lambda to fetch the binary digits.
This will help you to print binary number
Related
I'd simply like to convert a base-2 binary number string into an int, something like this:
>>> '11111111'.fromBinaryToInt()
255
Is there a way to do this in Python?
You use the built-in int() function, and pass it the base of the input number, i.e. 2 for a binary number:
>>> int('11111111', 2)
255
Here is documentation for Python 2, and for Python 3.
Just type 0b11111111 in python interactive interface:
>>> 0b11111111
255
Another way to do this is by using the bitstring module:
>>> from bitstring import BitArray
>>> b = BitArray(bin='11111111')
>>> b.uint
255
Note that the unsigned integer (uint) is different from the signed integer (int):
>>> b.int
-1
Your question is really asking for the unsigned integer representation; this is an important distinction.
The bitstring module isn't a requirement, but it has lots of performant methods for turning input into and from bits into other forms, as well as manipulating them.
Using int with base is the right way to go. I used to do this before I found int takes base also. It is basically a reduce applied on a list comprehension of the primitive way of converting binary to decimal ( e.g. 110 = 2**0 * 0 + 2 ** 1 * 1 + 2 ** 2 * 1)
add = lambda x,y : x + y
reduce(add, [int(x) * 2 ** y for x, y in zip(list(binstr), range(len(binstr) - 1, -1, -1))])
If you wanna know what is happening behind the scene, then here you go.
class Binary():
def __init__(self, binNumber):
self._binNumber = binNumber
self._binNumber = self._binNumber[::-1]
self._binNumber = list(self._binNumber)
self._x = [1]
self._count = 1
self._change = 2
self._amount = 0
print(self._ToNumber(self._binNumber))
def _ToNumber(self, number):
self._number = number
for i in range (1, len (self._number)):
self._total = self._count * self._change
self._count = self._total
self._x.append(self._count)
self._deep = zip(self._number, self._x)
for self._k, self._v in self._deep:
if self._k == '1':
self._amount += self._v
return self._amount
mo = Binary('101111110')
Here's another concise way to do it not mentioned in any of the above answers:
>>> eval('0b' + '11111111')
255
Admittedly, it's probably not very fast, and it's a very very bad idea if the string is coming from something you don't have control over that could be malicious (such as user input), but for completeness' sake, it does work.
A recursive Python implementation:
def int2bin(n):
return int2bin(n >> 1) + [n & 1] if n > 1 else [1]
If you are using python3.6 or later you can use f-string to do the
conversion:
Binary to decimal:
>>> print(f'{0b1011010:#0}')
90
>>> bin_2_decimal = int(f'{0b1011010:#0}')
>>> bin_2_decimal
90
binary to octal hexa and etc.
>>> f'{0b1011010:#o}'
'0o132' # octal
>>> f'{0b1011010:#x}'
'0x5a' # hexadecimal
>>> f'{0b1011010:#0}'
'90' # decimal
Pay attention to 2 piece of information separated by colon.
In this way, you can convert between {binary, octal, hexadecimal, decimal} to {binary, octal, hexadecimal, decimal} by changing right side of colon[:]
:#b -> converts to binary
:#o -> converts to octal
:#x -> converts to hexadecimal
:#0 -> converts to decimal as above example
Try changing left side of colon to have octal/hexadecimal/decimal.
For large matrix (10**5 rows and up) it is better to use a vectorized matmult. Pass in all rows and cols in one shot. It is extremely fast. There is no looping in python here. I originally designed it for converting many binary columns like 0/1 for like 10 different genre columns in MovieLens into a single integer for each example row.
def BitsToIntAFast(bits):
m,n = bits.shape
a = 2**np.arange(n)[::-1] # -1 reverses array of powers of 2 of same length as bits
return bits # a
For the record to go back and forth in basic python3:
a = 10
bin(a)
# '0b1010'
int(bin(a), 2)
# 10
eval(bin(a))
# 10
I traced the following code, and one part doesn't make sense to me:
def bin_rep(n: int) -> str:
"""Return the binary representation of n
>>> bin_rep(0)
"0"
>>> bin_rep(1)
"1"
>>> bin_rep(5)
"101"
"""
if n > 1:
return bin_rep(n // 2) + bin_rep(n % 2)
else:
return str(n)
The part that I don't understand is, why are we adding bin_rep(n//2) and bin_rep(n%2). I know that without the addition this won't work, but I can't wrap my head around why the addition exists there.
That's not addition. bin_rep returns a string. The + operator for type string is concatenation. Read this as
binary representation of n right-shifted a bit
concatenated with
binary representation of n's right-most bit
Does that clear it up?
bin_rep(n) returns the binary string representation of n.
The termination condition is n <= 1 which is bin_rep(0) -> '0' or bin_rep(1) -> '1'.
bin_rep(2) must return '10'. To do that it computes:
bin_rep(2 // 2) + bin_rep(n % 2)
bin_rep(1) + bin_rep(0)
'1' + '0' # String concatenation, not decimal addition!
'10'
... which is the correct answer. That should help clear up your understanding.
I'd simply like to convert a base-2 binary number string into an int, something like this:
>>> '11111111'.fromBinaryToInt()
255
Is there a way to do this in Python?
You use the built-in int() function, and pass it the base of the input number, i.e. 2 for a binary number:
>>> int('11111111', 2)
255
Here is documentation for Python 2, and for Python 3.
Just type 0b11111111 in python interactive interface:
>>> 0b11111111
255
Another way to do this is by using the bitstring module:
>>> from bitstring import BitArray
>>> b = BitArray(bin='11111111')
>>> b.uint
255
Note that the unsigned integer (uint) is different from the signed integer (int):
>>> b.int
-1
Your question is really asking for the unsigned integer representation; this is an important distinction.
The bitstring module isn't a requirement, but it has lots of performant methods for turning input into and from bits into other forms, as well as manipulating them.
Using int with base is the right way to go. I used to do this before I found int takes base also. It is basically a reduce applied on a list comprehension of the primitive way of converting binary to decimal ( e.g. 110 = 2**0 * 0 + 2 ** 1 * 1 + 2 ** 2 * 1)
add = lambda x,y : x + y
reduce(add, [int(x) * 2 ** y for x, y in zip(list(binstr), range(len(binstr) - 1, -1, -1))])
If you wanna know what is happening behind the scene, then here you go.
class Binary():
def __init__(self, binNumber):
self._binNumber = binNumber
self._binNumber = self._binNumber[::-1]
self._binNumber = list(self._binNumber)
self._x = [1]
self._count = 1
self._change = 2
self._amount = 0
print(self._ToNumber(self._binNumber))
def _ToNumber(self, number):
self._number = number
for i in range (1, len (self._number)):
self._total = self._count * self._change
self._count = self._total
self._x.append(self._count)
self._deep = zip(self._number, self._x)
for self._k, self._v in self._deep:
if self._k == '1':
self._amount += self._v
return self._amount
mo = Binary('101111110')
Here's another concise way to do it not mentioned in any of the above answers:
>>> eval('0b' + '11111111')
255
Admittedly, it's probably not very fast, and it's a very very bad idea if the string is coming from something you don't have control over that could be malicious (such as user input), but for completeness' sake, it does work.
A recursive Python implementation:
def int2bin(n):
return int2bin(n >> 1) + [n & 1] if n > 1 else [1]
If you are using python3.6 or later you can use f-string to do the
conversion:
Binary to decimal:
>>> print(f'{0b1011010:#0}')
90
>>> bin_2_decimal = int(f'{0b1011010:#0}')
>>> bin_2_decimal
90
binary to octal hexa and etc.
>>> f'{0b1011010:#o}'
'0o132' # octal
>>> f'{0b1011010:#x}'
'0x5a' # hexadecimal
>>> f'{0b1011010:#0}'
'90' # decimal
Pay attention to 2 piece of information separated by colon.
In this way, you can convert between {binary, octal, hexadecimal, decimal} to {binary, octal, hexadecimal, decimal} by changing right side of colon[:]
:#b -> converts to binary
:#o -> converts to octal
:#x -> converts to hexadecimal
:#0 -> converts to decimal as above example
Try changing left side of colon to have octal/hexadecimal/decimal.
For large matrix (10**5 rows and up) it is better to use a vectorized matmult. Pass in all rows and cols in one shot. It is extremely fast. There is no looping in python here. I originally designed it for converting many binary columns like 0/1 for like 10 different genre columns in MovieLens into a single integer for each example row.
def BitsToIntAFast(bits):
m,n = bits.shape
a = 2**np.arange(n)[::-1] # -1 reverses array of powers of 2 of same length as bits
return bits # a
For the record to go back and forth in basic python3:
a = 10
bin(a)
# '0b1010'
int(bin(a), 2)
# 10
eval(bin(a))
# 10
I am curious as to how I can change the number of bits to represent a binary number.
For example, say I want express decimal 1 to binary. I use:
bin(1) and get 0b1.
How can I get the return to say 0b01 or 0b001 or 0b0001 etc?
Use the Format String Syntax:
>>> format(1, '#04b')
'0b01'
>>> format(1, '#05b')
'0b001'
>>> format(1, '#06b')
'0b0001'
You can use str.zfill to pad the binary part:
def padded_bin(i, width):
s = bin(i)
return s[:2] + s[2:].zfill(width)
I don't believe there's a builtin way to do this. However, since bin just returns a string, you could write a wrapper function which modifies the string to have the right number of bits:
def binbits(x, n):
"""Return binary representation of x with at least n bits"""
bits = bin(x).split('b')[1]
if len(bits) < n:
return '0b' + '0' * (n - len(bits)) + bits
#
How can I add, subtract, and compare binary numbers in Python without converting to decimal?
You can convert between a string representation of the binary using bin() and int()
>>> bin(88)
'0b1011000'
>>> int('0b1011000', 2)
88
>>>
>>> a=int('01100000', 2)
>>> b=int('00100110', 2)
>>> bin(a & b)
'0b100000'
>>> bin(a | b)
'0b1100110'
>>> bin(a ^ b)
'0b1000110'
I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in. The fact that your python interpreter may store things as binary internally doesn't affect how you work with it - if you have an integer type, just use +, -, etc.
If you have strings of binary digits, you'll have to either write your own implementation or convert them using the int(binaryString, 2) function.
If you're talking about bitwise operators, then you're after:
~ Not
^ XOR
| Or
& And
Otherwise, binary numbers work exactly the same as decimal numbers, because numbers are numbers, no matter how you look at them. The only difference between decimal and binary is how we represent that data when we are looking at it.
Binary, decimal, hexadecimal... the base only matters when reading or outputting numbers, adding binary numbers is just the same as adding decimal number : it is just a matter of representation.
Below is a re-write of a previously posted function:
def addBinary(a, b): # Example: a = '11' + b =' 100' returns as '111'.
for ch in a: assert ch in {'0','1'}, 'bad digit: ' + ch
for ch in b: assert ch in {'0','1'}, 'bad digit: ' + ch
sumx = int(a, 2) + int(b, 2)
return bin(sumx)[2:]
'''
I expect the intent behind this assignment was to work in binary string format.
This is absolutely doable.
'''
def compare(bin1, bin2):
return bin1.lstrip('0') == bin2.lstrip('0')
def add(bin1, bin2):
result = ''
blen = max((len(bin1), len(bin2))) + 1
bin1, bin2 = bin1.zfill(blen), bin2.zfill(blen)
carry_s = '0'
for b1, b2 in list(zip(bin1, bin2))[::-1]:
count = (carry_s, b1, b2).count('1')
carry_s = '1' if count >= 2 else '0'
result += '1' if count % 2 else '0'
return result[::-1]
if __name__ == '__main__':
print(add('101', '100'))
I leave the subtraction func as an exercise for the reader.
For example, 00000011 - 00000001 = 00000010
You can remove the zeroes and then add them again after you do your calculation! This works very easy.
If your binary is stored as a string then you can convert to int which will automatically strip the zeroes from the start. After you have your answer you can turn it back into a string and add the zeroes to the start.
Not sure if helpful, but I leave my solution here:
class Solution:
# #param A : string
# #param B : string
# #return a strings
def addBinary(self, A, B):
num1 = bin(int(A, 2))
num2 = bin(int(B, 2))
bin_str = bin(int(num1, 2)+int(num2, 2))
b_index = bin_str.index('b')
return bin_str[b_index+1:]
s = Solution()
print(s.addBinary("11", "100"))
x = x + 1
print(x)
a = x + 5
print(a)
I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in.