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. ;)
Related
I have a string of numbers with no whitespaces like this:
s = '12.2321.4310.85'
I know that the format for each number is F5.2 (I am reading the string from a FORTRAN code output)
I need to obtain the following list of numbers based on s:
[12.23,21.43,10.85]
How can I do this in python?
Thanks in advance for any help!
Slice the string into chunks of 5 characters. Convert each chunk to float.
>>> [float(s[i:i+5]) for i in range(0, len(s), 5)]
[12.23, 21.43, 10.85]
If you are really sure of the format, and that will always be handed in that way then using a step of 5 in your loop might work:
s = '12.2321.4310.85'
output = []
for i in range(0,len(s),5):
output.append(float(s[i:i+5]))
print(output)
Output:
[12.23, 21.43, 10.85]
I think the safest way is to rely on . points. Because we know that every floating point should have one fraction and always there are two fraction numbers (there might be values like 1234.56 and 78.99 in the data that generates s = "1234.5678.99"). But we are not sure how many digits are before .. So we can extract values one by one based on ..
s = '12.2321.4310.85'
def extractFloat(s):
# Extracts the first floating number with 2 floatings from the string
return float( s[:s.find('.')+3]) , s[s.find('.')+3:]
l = []
while len(s) > 0:
value, s = extractFloat(s)
l.append(value)
print(l)
# Output:
# [12.23, 21.43, 10.85]
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
When adding decimal places, it's as simple as
john = 2
johnmod = format(john, '.2f')
print(johnmod)
and I get 2.00 back, as expected. But, what's the format spec for adding preceding zeros? I would like for the output to be 0002, and the only spec I've found with Google for that is using %04d, which did not work. If it matters, I am running Python 3.3 on windows.
Several Pythonic ways to do this,:
First using the string formatting minilanguage, using your attempted method, first zero means the fill, the 4 means to which width:
>>> format(2, "04")
'0002'
Also, the format minilanguage:
>>> '{0:04}'.format(2)
'0002'
the specification comes after the :, and the 0 means fill with zeros and the 4 means a width of four.
New in Python 3.6 are formatted string literals:
>>> two = 2
>>> f'{two:04}'
'0002'
Finally, the str.zfill method is custom made for this:
>>> str(2).zfill(4)
'0002'
Use zfill:
john = 2
johnmod = str(john).zfill(4)
print(johnmod) # Prints: 0002
You were nearly there:
johnmod = format(john, "04d")
format(john, '05.2f')
You can add the leading 0 to a floating point f format as well, but you must add the trailing digits (2) and the decimal point to the total.
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.
I am trying to increment a binary sequence in python while maintaining the bit length.
So far I am using this piece of code...
'{0:b}'.format(long('0100', 2) + 1)
This will take the binary number, convert it to a long, adds one, then converts it back to a binary number. Eg, 01 -> 10.
However, if I input a number such as '0100', instead of incrementing it to '0101', my code
increments it to '101', so it is disregarding the first '0', and just incrementing '100'
to '101'.
Any help on how to make my code maintain the bit length will be greatly appreciated.
Thanks
str.format lets you specify the length as a parameter like this
>>> n = '0100'
>>> '{:0{}b}'.format(long(n, 2) + 1, len(n))
'0101'
That's because 5 is represented as '101' after conversion from int(or long) to binary, so to prefix some 0's before it you've use 0 as filler and pass the width of the initial binary number while formatting.
In [35]: b='0100'
In [36]: '{0:0{1:}b}'.format(long(b, 2) + 1,len(b))
Out[36]: '0101'
In [37]: b='0010000'
In [38]: '{0:0{1:}b}'.format(long(b, 2) + 1,len(b))
Out[38]: '0010001'
This is probably best solved using format strings. Get the length of your input, construct a format string from it, and then use it to print the incremented number.
from __future__ import print_function
# Input here, as a string
s = "0101"
# Convert to a number
n = long(s, 2)
# Construct a format string
f = "0{}b".format(len(s))
# Format the incremented number; this is your output
t = format(n + 1, f)
print(t)
To hardcode to four binary places (left-padded by 0) you would use 04b, for five you would use 05b, etc. In the code above we just get the length of the input string.
Oh, and if you input a number like 1111 and add 1 you'll get 10000 since you need an extra bit to represent that. If you want to wrap around to 0000 do t = format(n + 1, f)[-len(s):].