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
Related
I have this problem:
n = int(input("Enter Hexadecimal Number: ")
print(0xn)
I found that it works when n is already defined...
Also how to convert it when the number is a string like 2ABF
The 0b, 0o, and 0x modifiers only work with int literals, by which I mean, when you're writing the integer literally in code. You can't simply apply them to a variable that already has a value, as integers aren't stored with any particular base in mind (that only matters when you display them somehow).
When converting a string to an int, you can specify the base it's in as a second argument:
n = int("AF", 16)
# 175
For bases beyond 16, it continues to use the rest of the alphabet, up to 36, after which point it refuses to continue because there are no more letters, forcing you to write your own.
When converting an int to a string, there's no particular one-size-fits-all method. However, for the common bases in particular, there are built-in functions:
bin(n) # '0b10101111' - base 2
oct(n) # '0o257' - base 8
hex(n) # '0xaf' - base 16
You can then do the usual string manipulation on these to get rid of the first two characters and make the hex all-uppercase, if you want:
print(hex(n)[2:].upper())
# AF
Try as follow:
n = input("Enter Hexadecimal Number: ")
print(hex(int('0x' + n, 16)))
x = 64
var_in_bin_format = bin(64)
print(var_in_bin_format)
#Output
#0b1000000
#Desired Output -- > should always be in 8 bit format
#0b01000000
def call_another_api(var_in_bin_format):
pass
In Python, I need to call an API that expects its parameter to be always in 8 bit format regardless of the value of the decimal number?
I am not that good in bit manipulation so I am thinking if there is something I can do here?
How can I do this? I cannot use the format() function as it will convert the value into a string representation and the API that I am calling will alert me that it is not in the correct format.
Even though you say that you can't use format() because it returns a string, I'm going to post this because that's also what bin() does. bin(x) is equivalent to format(x, '#b'). I'd guess that you haven't added the '#', which means you won't have '0b' leading the value.
The Python 3 documentation for bin() actually gives a pretty strong hint about how you might do this, using format instead.
If you know that the value passed will not be negative, you can use the format string '#010b':
format(x, '#010b')
Breaking this down:
'b' means that the number will be a string binary representation.
'10' means that the entire string will be 10 characters long, two for '0b' and 8 for the value.
'0' makes it pad with '0' instead of ' '.
'#' will add the '0b' prefix, as done by bin().
Note that this assumes that the number is an integer in the range [0, 255]. Integers outside this range will generate valid representations, but will not match the format expected, and may have a leading '-'. Objects of type float can not be converted with the 'b' format code. I assume that these are not problems, given what your intended output is, but it might be a good idea to add an explicit check to throw a ValueError if the value is less than 0 or greater than 255.
If you're in Python 3.6+, you could also use f-strings:
f'{x:#010b}'
Is is not possible to convert all decimal numbers to 8 bit. You can only convert numbers from 0 to 255 in 8 bits.
There is an unexpected output when I am dealing with binary number in Python 3.
We can easily convert any integer to binary by built-in bin() function. For example:
>>>bin(4243125)
Here's the issue when I try to add 2 binary function:
>>>bin(x)+bin(y)
The output is concatenation of two binary number, not addition of binary number. The output of binary function has become a string.
Addition in a binary function works fine:
>>>bin(x+y)
And try to add two binary number without bin() is viable too:
>>>0b100+0b10111
What is the reasons/purposes of setting a bin() output to a string?
bin, like hex, converts a decimal to a string literal representing the number in that base.
If you want to add 2 numbers together simply do so:
x = 10
y = 2
x + y
If you want to take binary strings as input and add them together convert them back from string literals with int base 2, like this:
x = bin(10)
y = bin(2)
int(x, 2) + int(y, 2)
If you're looking to do bitwise operations look at the Python bitwise operators:
https://wiki.python.org/moin/BitwiseOperators
How to convert floating point number to base-16 numbers, 8 hexadecimal digits per 32-bit FLP number in python?
eg : input = 1.2717441261e+20 output wanted : 3403244E
If you want the byte values of the IEEE-754 representation, the struct module can do this:
>>> import struct
>>> f = 1.2717441261e+20
>>> struct.pack('f', f)
'\xc9\x9c\xdc`'
This is a string version of the bytes, which can then be converted into a string representation of the hex values:
>>> struct.pack('f', f).encode('hex')
'c99cdc60'
And, if you want it as a hex integer, parse it as such:
>>> s = struct.pack('f', f).encode('hex')
>>> int(s, 16)
3382500448
To display the integer as hex:
>>> hex(int(s, 16))
'0xc99cdc60'
Note that this does not match the hex value in your question -- if your value is the correct one you want, please update the question to say how it is derived.
There are several possible ways to do so, but none of them leads to the result you wanted.
You can code this float value into its IEEE binary representation. This leads indeed to a 32 bit number (if you do it with single precision). But it leads to different results, no matter which endianness I suppose:
import struct
struct.pack("<f", 1.2717441261e+20).encode("hex")
# -> 'c99cdc60'
struct.pack(">f", 1.2717441261e+20).encode("hex")
# -> '60dc9cc9'
struct.unpack("<f", "3403244E".decode("hex"))
# -> (687918336.0,)
struct.unpack(">f", "3403244E".decode("hex"))
# -> (1.2213533295835077e-07,)
As the other one didn't fit result-wise, I'll take the other answers and include them here:
float.hex(1.2717441261e+20)
# -> '0x1.b939919e12808p+66'
Has nothing to do with 3403244E as well, so maybe you want to clarify what exactly you mean.
There are surely other ways to do this conversation, but unless you specify which method you want, no one is likely to be able to help you.
There is something wrong with your expected output :
import struct
input = 1.2717441261e+20
buf = struct.pack(">f", input)
print ''.join("%x" % ord(c) for c in struct.unpack(">4c", buf) )
Output :
60dc9cc9
Try float.hex(input) if input is already a float.
Try float.hex(input). This should convert a number into a string representing the number in base 16, and works with floats, unlike hex(). The string will begin with 0x however, and will contain 13 digits after the decimal point, so I can't help you with the 8 digits part.
Source: http://docs.python.org/2/library/stdtypes.html#float.hex
I have the variable Number which is equal to "0b11001010" and I want it to be the type int like a normal binary is stored e.g. 0b11001010
Number = "0b11001010"
NewNumber = 0b11001010
is there a really simple way and I am overlooking it?
Thanks.
In python you can only create it as a binary value (as a syntactic sugar), it will be converted into an integer immediately. Try it for yourself:
>>> 0b11001010
202
The same thing will happen with octal and hexadecimal values. So you can convert your binary string to an integer, with the int() function's base argument like:
>>> int('0b11001010', 2)
202
After the conversion you can do any operations on it -- just like with an integer, since it is an integer.
Of course you can convert it back at any time to a binary string, with the builtin bin() function:
>>> bin(202)
0b11001010