Making a function to manipulate an integer - python

I want to make a function to transform an integer.
For example:
d = "1209834"
I want to , in one function, turn it into an integer, then turn it into a binary, then strip off the 0b prefix. So I'd just get 100100111010111101010 as a result when the function is applied.

Can use built-in bin and int
>>> bin(int(d))[2:]
'100100111010111101010'

You can do this in one line:
d = "1209834"
int_d = int(d)
binary_d = "{0:b}".format(int_d) # binary of d as a string

Related

How to convert hexadecimal string to character with that code point?

I have the string x = '0x32' and would like to turn it into y = '\x32'.
Note that len(x) == 4 and len(y) == 1.
I've tried to use z = x.replace("0", "\\"), but that causes z = '\\x32' and len(z) == 4. How can I achieve this?
You do not have to make it that hard: you can use int(..,16) to parse a hex string of the form 0x.... Next you simply use chr(..) to convert that number into a character with that Unicode (and in case the code is less than 128 ASCII) code:
y = chr(int(x,16))
This results in:
>>> chr(int(x,16))
'2'
But \x32 is equal to '2' (you can look it up in the ASCII table):
>>> chr(int(x,16)) == '\x32'
True
and:
>>> len(chr(int(x,16)))
1
Try this:
z = x[2:].decode('hex')
The ability to include code points like '\x32' inside a quoted string is a convenience for the programmer that only works in literal values inside the source code. Once you're manipulating strings in memory, that option is no longer available to you, but there are other ways of getting a character into a string based on its code point value.
Also note that '\x32' results in exactly the same string as '2'; it's just typed out differently.
Given a string containing a hexadecimal literal, you can convert it to its numeric value with int(str,16). Once you have a numeric value, you can convert it to the character with that code point via chr(). So putting it all together:
x = '0x32'
print(chr(int(x,16)))
#=> 2

Remove the 0b in binary

I am trying to convert a binary number I have to take out the 0b string out.
I understand how to get a bin number
x = 17
print(bin(17))
'0b10001'
but I want to take the 0b in the string out and I am having some issues with doing this. This is going to be within a function returning a binary number without the 0b.
Use slice operation to remove the first two characters.
In [1]: x = 17
In [2]: y = bin(x)[2:]
In [3]: y
Out[3]: '10001'
use python string slice operation.
a = bin(17)
b = bin(17)[2:]
to format this to 8-bits use zfill.
c = b.zfill(8)
It's easy just make this function:
def f(n):print('{:0b}'.format(n))
f(17)
>>> 10001
format(17, 'b')
>>> '10001'
Use the format() builtin. It also works for hexadecimal, simply replace 'b' with 'x'.
https://docs.python.org/3/library/functions.html#format
bin(n).replace("0b", "")
This one is using replace
Where n is the provided decimal
with Python 3.6 you can use f-strings
print( f'{x:b}' )
'10001'
I do not know why nobody suggested using lstrip.
integer = 17
bit_string = bin(integer)
final = bit_string.lstrip('-0b') # minus to also handle negations
print(final) # prints 10001
inhexa=(hexanum.get()) # gets the hexa value
dec = int(inhexa,16) #changes the base ensures conversion into base 16 to interger
b=bin(dec)[2:] #converts int/dec into binary and shows string except first two digits
print (bin(int(input().strip()))[2:])
Pythonic way to solve. ;)

How to append \ join binary digits to a variable

How can i append binary digits to a final variable in python
a = self.allcheckboxes[0].isChecked() # 1
b = self.allcheckboxes[1].isChecked() # 0
c = self.allcheckboxes[2].isChecked() # 1
d = self.allcheckboxes[3].isChecked() # 0
final_value = 010+a+b+c+d
# iam expecting something like 0101010 in binary
I am assuming you just want a binary looking string, rather than an integer with the relevant bits set, if so you could use the following for checkboxes 10 to 14:
final_value = ''.join('1' if checkbox.isChecked() else '0' for checkbox in self.allcheckboxes[10:15])
This could then be converted to an integer and printed as hex if required as follows:
integer_value = int(final_value, 2)
print '{:x}'.format(integer_value)
You can use operator.itemgetter and operator.attrgetter within map function to do all the codes in one line and use str.join() to join the result :
from operator import itemgetter,attrgetter
''.join(map(attrgetter('isChecked'),itemgetter(0,1,2,3)(self.allcheckboxes)))
Also note that there is no binary type in python, when you get the concatenated string, based on your aim and the functions which you are dialing for, you can tread with this string as a binary number.
For example if you want to convert it to an integer you can use int function by passing 2 as its base:
>>> int('0101',2)
5

Length of hexadecimal number

How can we get the length of a hexadecimal number in the Python language?
I tried using this code but even this is showing some error.
i = 0
def hex_len(a):
if a > 0x0:
# i = 0
i = i + 1
a = a/16
return i
b = 0x346
print(hex_len(b))
Here I just used 346 as the hexadecimal number, but my actual numbers are very big to be counted manually.
Use the function hex:
>>> b = 0x346
>>> hex(b)
'0x346'
>>> len(hex(b))-2
3
or using string formatting:
>>> len("{:x}".format(b))
3
While using the string representation as intermediate result has some merits in simplicity it's somewhat wasted time and memory. I'd prefer a mathematical solution (returning the pure number of digits without any 0x-prefix):
from math import ceil, log
def numberLength(n, base=16):
return ceil(log(n+1)/log(base))
The +1 adjustment takes care of the fact, that for an exact power of your number base you need a leading "1".
As Ashwini wrote, the hex function does the hard work for you:
hex(x)
Convert an integer number (of any size) to a hexadecimal string. The result is a valid Python expression.

How to convert a string representing a binary fraction to a number in Python

Let us suppose that we have a string representing a binary fraction such as:
".1"
As a decimal number this is 0.5. Is there a standard way in Python to go from such strings to a number type (whether it is binary or decimal is not strictly important).
For an integer, the solution is straightforward:
int("101", 2)
>>>5
int() takes an optional second argument to provide the base, but float() does not.
I am looking for something functionally equivalent (I think) to this:
def frac_bin_str_to_float(num):
"""Assuming num to be a string representing
the fractional part of a binary number with
no integer part, return num as a float."""
result = 0
ex = 2.0
for c in num:
if c == '1':
result += 1/ex
ex *= 2
return result
I think that does what I want, although I may well have missed some edge cases.
Is there a built-in or standard method of doing this in Python?
The following is a shorter way to express the same algorithm:
def parse_bin(s):
return int(s[1:], 2) / 2.**(len(s) - 1)
It assumes that the string starts with the dot. If you want something more general, the following will handle both the integer and the fractional parts:
def parse_bin(s):
t = s.split('.')
return int(t[0], 2) + int(t[1], 2) / 2.**len(t[1])
For example:
In [56]: parse_bin('10.11')
Out[56]: 2.75
It is reasonable to suppress the point instead of splitting on it, as follows. This bin2float function (unlike parse_bin in previous answer) correctly deals with inputs without points (except for returning an integer instead of a float in that case).
For example, the invocations bin2float('101101'), bin2float('.11101'), andbin2float('101101.11101')` return 45, 0.90625, 45.90625 respectively.
def bin2float (b):
s, f = b.find('.')+1, int(b.replace('.',''), 2)
return f/2.**(len(b)-s) if s else f
You could actually generalize James's code to convert it from any number system if you replace the hard coded '2' to that base.
def str2float(s, base=10):
dot, f = s.find('.') + 1, int(s.replace('.', ''), base)
return f / float(base)**(len(s) - dot) if dot else f
You can use the Binary fractions package. With this package you can convert binary-fraction strings into floats and vice-versa.
Example:
>>> from binary_fractions import Binary
>>> float(Binary("0.1"))
0.5
>>> str(Binary(0.5))
'0b0.1'
It has many more helper functions to manipulate binary strings such as: shift, add, fill, to_exponential, invert...
PS: Shameless plug, I'm the author of this package.

Categories

Resources