I already tried converting it to a string, adding 0 to it, but it still only shows me the decimal value, how can I make it show me its binary value?
If I try this:
binary = 0b010
print(binary)
or this:
binary = 0b010
print(str(binary))
which outputs this:
2
I also tried this:
binary = 0b010
print("{0:b}".format(binary))
which outputs this:
10
Desired output:
010
The bad part is that it does not fill in the number of 0 on the left, it gives me an output of 10 when I want 010, but I want it to show the number of 0 possible for any binary that I put.
I'm new to Python, but every time I look for how to do it, it only appears to me as converting from integer to binary and showing it. But I can't use the bin() function, so I resorted to asking it here directly, thanks for your understanding.
You have a couple of ways of going about it.
The one that fits your use case the best is the format() method:
binary = 0b010
print("{:03b}".format(binary))
Which outputs:
010
Changing the 3 in {:03b} will change the minimum length of the output(it will add leading zeros if needed).
If you want to use it without leading zeros you can simply do {:b}.
You can try defining your own function to convert integers to binary:
def my_bin(x):
bit = ''
while x:
bit += str(x % 2)
x >>= 1
return '0' + bit[::-1]
binary = 0b010
print(my_bin(binary))
Output:
010
Related
I can't quite find a solution for this.
Basically what I've done so far is created a string which represents the binary version of x amount of characters padded to show all 8 bits.
E.g. if x = 2 then I have 0101100110010001 so 8 digits in total. Now I have 2 strings of the same length which I want to XOR together, but python keeps thinking it's a string instead of binary. If I use bin() then it throws a wobbly thinking it's a string which it is. So if I cast to an int it then removes the leading 0's.
So I've already got the binary representation of what I'm after, I just need to let python know it's binary, any suggestions?
The current function I'm using to create my binary string is here
for i in origAsci:
origBin = origBin + '{0:08b}'.format(i)
Thanks in advance!
Use Python's int() function to convert the string to an integer. Use 2 for the base parameter since binary uses base 2:
binary_str = '10010110' # Binary string
num = int(binary_str, 2)
# Output: 150
Next, use the bin() function to convert the integer to binary:
binary_num = bin(num)
# Output: 0b10010110
I have to plot i a figure some number with a specific number of significant digits even when all are zero. I mean, if I have a number like 12.00000000, I would like to print 12.000 and not 12.
This is what I have tried:
Given a number read from a file
a='23.00000000'
I convert it to float and I specify the number of digits as
b = float(a)
float("{:.3f}".format(b))
However, this is the results:
Out[]: 23.0
while I would like to have
Out[]: 23.000
The problem is in line:
float("{:.3f}".format(b))
"{:.3f}".format(23.0) will give you '23.000', but then you're converting it to float again, which removes the trailing 0's.
To correct it, you can do:
"{:.3f}".format(b)
and it will result in: '23.000'
I think your problem is with the plotting part. You might be able to change the precision of the plot. However, I think you can use format:
Using format:
a = '23.00000000'
b = float(a)
b = format(b, '.3f')
I need to extract some bits from an integer. However how many bits to be extracted is not fixed.
For example a certain code is generating 2 numbers a and b. What I want is a code that could do
c = a[b-1:0]
One of the methods I read about on the web is w say b is a fixed value 3, a simple method to do is
c=bin (a >> 0 & 0b111 )
But this could be done if value of b is fixed 3 i.e we right shift based on known fixed number of bits being anded i.e 3.
But what if the "3" is not fixed? During run time I may need lower 4 bits or 3 bits or 2 bits...anything.
I thing I tried and hoped it would work is
x = bin(a)
c= x[b-1:0]
But even this doesn't work.
Some of your code is trying to access the bits of an integer using slice notation ([:]) but that only works with sequences, not integers.
First you need to decide if you want to work with a string representation of your number in binary, or an integer representation, and be consistent about that. Let's start with a string representation in binary. a is the input number, b is the number of bits.
>>> a = 35
>>> x = bin(a)
>>> x
'0b100011'
Now you want a string representation in binary of the integer that is the rightmost b positions of this string:
>>> b = 3
>>> x[-b:]
'011'
Deprived of its 0b prefix, this string of 3 digits could mean anything. Some examples: in binary, 3; in decimal, 11; in octal 9; in hex, 17. We know from reading the code that it is part of the output from a bin() call, but the string doesn't carry that information around with it. The 3 digits mean whatever you intend them to mean.
If you want to convert that into something you can do arithmetic with, you call int() to convert it back to an integer. But because int() can't tell that the representation is supposed to be binary, do this:
>>> int(x[-b:],2)
3
The 2 passed as the second parameter to int() specifies what base the string is supposed to be in. It's not specifying a conversion: it's specifying an interpretation. It's optional, but if you leave it out then int() will use the default base, which is of course 10.
>>> int(x[-b:])
11
This happens because without any indication of the base, 011 means "eleven, with a leading zero". And int() converts a string to an integer: just integer, not base-10 integer. The internal representation of integer is only converted to base 10 when you ask the interpreter to display it. (Internally, Python integers actually use base 2**30, but most of us never have to think about that much, and I recommend you don't either.)
Now consider just working with integers. If the number of bits you want to mask off is b then (as johnrsharpe points out), you can get the corresponding mask using (2**b - 1):
>>> 2**b - 1
7
Just to demonstrate this is what you actually want:
>>> bin(2**b - 1)
'0b111'
Then you can use the bitwise & operator to get the digits you want. This works sort of opposite to the string method: instead of chopping off the 3 digits that you want, you instead use & to set the digits you don't want to zero:
a = 100011
b = 000111 &
------
000011
Then you can obtain the result directly without having to go through a string conversion and taking slices and converting back to integer:
>>> a & 2**b - 1
3
As you can see this gives the same result in one step. In your question I also see a right shift operator >> but because you are shifting zero positions it does nothing. If you also want to accept a shift quantity, say s, then in the examples above, use (a >> s) instead of a.
From the question, it is not very clear what you actually want to do, but what I understood is that you want to extract 'b' last bits from 'a'.
If two numbers are 'a' and 'b':
First, convert 'a' into binary:
x = bin(a)[2:]
Extracting last b bits from a:
p = x[len(x)-b:]
If you actually want the (lower) bits of the integer value: something like this could do it:
def getbits(value, numbits):
""" Extract the lower numbits of value. """
return value & (2 ** numbits - 1)
value = 0b010011000111
for i in range(value.bit_length()+1):
print('getbits({:012b}, {:2d}): {:12b}'.format(value, i, getbits(value, i)))
Output:
getbits(010011000111, 0): 0
getbits(010011000111, 1): 1
getbits(010011000111, 2): 11
getbits(010011000111, 3): 111
getbits(010011000111, 4): 111
getbits(010011000111, 5): 111
getbits(010011000111, 6): 111
getbits(010011000111, 7): 1000111
getbits(010011000111, 8): 11000111
getbits(010011000111, 9): 11000111
getbits(010011000111, 10): 11000111
getbits(010011000111, 11): 10011000111
I am trying to make a program that converts a given integer(limited by the value 32 bit int can hold) into 32 bit binary number. For example 1 should return (000..31times)1. I have been searching the documents and everything but haven't been able to find some concrete way. I got it working where number of bits are according to the number size but in String. Can anybody tell a more efficient way to go about this?
'{:032b}'.format(n) where n is an integer. If the binary representation is greater than 32 digits it will expand as necessary:
>>> '{:032b}'.format(100)
'00000000000000000000000001100100'
>>> '{:032b}'.format(8589934591)
'111111111111111111111111111111111'
>>> '{:032b}'.format(8589934591 + 1)
'1000000000000000000000000000000000' # N.B. this is 33 digits long
You can just left or right shift integer and convert it to string for display if you need.
>>> 1<<1
2
>>> "{:032b}".format(2)
'00000000000000000000000000000010'
>>>
or if you just need a binary you can consider bin
>>> bin(4)
'0b100'
Say for example the number you want to convert into 32 bit binary is 4. So, num=4.
Here is the code that does this: "s" is the empty string initially.
for i in range(31,-1,-1):
cur=(num>>i) & 1 #(right shift operation on num and i and bitwise AND with 1)
s+=str(cur)
print(s)#s contains 32 bit binary representation of 4(00000000000000000000000000000100)
00000000000000000000000000000100
Lets say
a = 4
print(bin(a)) # 0b101
For the output you may append 0s from LSB to till 101 to get the 32bit address for the integer - 4.
If you don't want 0b you may slice it
print(bin(a)[-3:]) # 101
Scratching my head at what seems like the simplest thing ever.
I am working on a polynomial calculator and have been testing it with some values, but python is not adding these two values the way it needs to be.
ans_2 = (-0.423604188255 + 0.42368554704)
print("Ans 2 = : " + str(ans_2))
I am getting this answer:
Ans 2 = : 8.1358785e-05
But I should be getting an answer like this:
=0.00009
Is there something I am doing wrong?
The value 8.1358785e-05 is scientific notation for the value .000081358785. The print function automatically converts to scientific notation for floats under a certain value.
If you want it to print out the value you're looking for, you need to format the string to tell the print function exactly what you're looking for. You can do that like this
In [11]: ans_2 = (-0.423604188255 + 0.42368554704)
In [12]: print("Ans 2 = : {:.7f} ".format(ans_2))
Ans 2 = : 0.0000814
This will format the string to include seven digits after the decimal.
The value 8.1358785e-05 is just another representation of 0.000081358785.
Whenever you see 'e' in your number means that your value was multiplied by 10 to power of anything that goes after 'e'.
In your case it will be:
8.1358785 * 10 ^ (-5) = 0.000081358785
For more info look there
Possibly you are overlooking that there is -ve sign before the first number. That's why you seem to expect the function to return 0.847289735295 (sum of absolute values of operands) instead of the correct answer (their difference according to their sign)