convert from string object to binary value python - python

I have a string that hold a binary number as a string
string = '0b100111'
I want to have that value not be a string type but a value (pseudo-code)
bin(string) = 0b100111
Any pythoners know an easy way to do this?
It is all part of this code for a Codecademy: (After answer implemented)
def flip_bit(number,n):
if type(number)==type('s'):
number = int(number,2)
mask=(0b1<<n-1)
print bin(mask)
print mask
desired = bin(number^mask)
return desired
flip_bit('0b111', 2)

What about calling int function with base 2?
>>>s = '0b100111'
>>>b = int(s, 2)
>>>print b
39

you can make it binary by putting a b before the quotes:
>>> s = b'hello'
>>> s.decode()
'hello'

I'm afraid that making it as idealised in your question is impossible. As what you want is a a series of characters, it can only be a string (or you could convert it to an integer). But it is still workable as a number with built in functions- for example:
num1 = '0b0110'
num1 = '0b0101'
result = int(num1, 2) + int(num2, 2)
print(bin(result))
The only way you could have that synatx in your code is if that binary number became a name itself. Python only supports the manipulation of numbers in base 10, as it only interprets number inputs in that format. Otherwise it is a string within which numbers cannot be manipulated.

Related

python how convert a binary string to a binary number [duplicate]

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

String of bits to binary format Python

This seems really simple but I can't figure it out.
I have a string of bits in a string format and want to convert it to a binary format.
I assumed placing the string inside of the bin() function would work but it doesn't.
string = "01101"
print(bin(string))
string = "01101"
print(bin(int(string,2)))
It depends what you mean by binary format.
Here's a few examples of what you can do:
>>> int('01101', 2)
13
>>> number = 13
>>> bin(number)
'0b1101'
>>> oct(number)
'0o15'
>>> hex(number)
'0xd'
>>> f'{number:08b}'
'00001101'

How to get range of bits from byte in python? [duplicate]

I'm trying to convert an integer to binary using the bin() function in Python. However, it always removes the leading zeros, which I actually need, such that the result is always 8-bit:
Example:
bin(1) -> 0b1
# What I would like:
bin(1) -> 0b00000001
Is there a way of doing this?
Use the format() function:
>>> format(14, '#010b')
'0b00001110'
The format() function simply formats the input following the Format Specification mini language. The # makes the format include the 0b prefix, and the 010 size formats the output to fit in 10 characters width, with 0 padding; 2 characters for the 0b prefix, the other 8 for the binary digits.
This is the most compact and direct option.
If you are putting the result in a larger string, use an formatted string literal (3.6+) or use str.format() and put the second argument for the format() function after the colon of the placeholder {:..}:
>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'
As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using format():
>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format") # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193
But I'd use that only if performance in a tight loop matters, as format(...) communicates the intent better.
If you did not want the 0b prefix, simply drop the # and adjust the length of the field:
>>> format(14, '08b')
'00001110'
>>> '{:08b}'.format(1)
'00000001'
See: Format Specification Mini-Language
Note for Python 2.6 or older, you cannot omit the positional argument identifier before :, so use
>>> '{0:08b}'.format(1)
'00000001'
I am using
bin(1)[2:].zfill(8)
will print
'00000001'
When using Python >= 3.6, you can use f-strings with string formatting:
>>> var = 23
>>> f"{var:#010b}"
'0b00010111'
Explanation:
var the variable to format
: everything after this is the format specifier
# use the alternative form (adds the 0b prefix)
0 pad with zeros
10 pad to a total length off 10 (this includes the 2 chars for 0b)
b use binary representation for the number
You can use the string formatting mini language (Thanks to #Martijn Pieters for the suggestion) idea:
def binary(num, length=8):
return format(num, '#0{}b'.format(length + 2))
Demo:
print(binary(1))
Output:
'0b00000001'
I like python f-string formatting for a little more complex things like using a parameter in format:
>>> x = 5
>>> n = 8
>>> print(f"{x:0{n}b}")
00000101
Here I print variable x with following formatting: I want it to be left-filled with 0 to have length = n, in b (binary) format. See Format Specification Mini-Language from previous answers for more.
Sometimes you just want a simple one liner:
binary = ''.join(['{0:08b}'.format(ord(x)) for x in input])
Python 3
You can use something like this
("{:0%db}"%length).format(num)
You can use zfill:
print str(1).zfill(2)
print str(10).zfill(2)
print str(100).zfill(2)
prints:
01
10
100
I like this solution, as it helps not only when outputting the number, but when you need to assign it to a variable...
e.g. -
x = str(datetime.date.today().month).zfill(2) will return x as '02' for the month of feb.
You can use string.rjust method:
string.rjust(length, fillchar)
fillchar is optional
and for your Question you can write like this
'0b'+ '1'.rjust(8,'0)
so it will be '0b00000001'

Forming a byte string in Python

I am creating a method in Python whereby it will take a number which will form a byte string that will then get sent to the Arduino. However whenever I try, the escape character is always included in the final byte string.
Here is the snippet of the code I am using:
num = 5
my_str = '\\x4' + str(num)
my_str.encode('utf-8')
Result:
b'\\x45'
I tried another method:
num2 = 5
byte1 = b'\\x4'
byte2 = bytes(str(num2), 'ISO-8859-1')
new_byte = byte1 + byte2
new_byte
Result:
b'\\x45'
Trying yet in a different way:
num = 5
u = chr(92) + 'x4' + str(num)
u.encode('ISO-8859-1')
Result:
b'\\x45'
I would like to get the byte string to be b'\x45' without the escape character but not really sure what I have missed. I will appreciate any pointers on how I can achieve this.
Your problem is that you have already escaped the backslash. It is not recommended to construct a literal using an unknown variable, especially if there's a simpler way, which there is:
def make_into_bytes(n):
return bytes([64 + n])
print(make_into_bytes(5))
This outputs
b'E'
Note that this isn't a bug, as this is simply the value of 0x45:
>>> b'\x45'
b'E'
The way this function works is basically just doing it by hand. Prepending '4' to a hex string (of length 1) is the same as adding 4 * 16 to it, which is 64. I then construct a bytes object out of this. Note that I assume n is an integer, as in your code. If n should be a digit like 'a', this would be the integer 10.
If you want it to work on hex digits, rather than on integer digits, you would need to change it to this:
def make_into_bytes(n):
return bytes([64 + int(n, 16)])
print(make_into_bytes('5'))
print(make_into_bytes('a'))
with output
b'E'
b'J'
This quite simply converts the digit from base 16 first.
You can use the built-in function chr() to convert an integer to the corresponding character:
>>> chr(0x40 + 5)
'E'
Alternatively, if you just one to get the n-th letter of the alphabet, it might be more readable to use str.ascii_uppercase
>>> string.ascii_uppercase[5 - 1]
'E'
Note that the results in this answer are strings in Python 3, not bytes objects. Simply calling .encode() on them will convert them to bytes.

How do I convert a string of bits to a hex string in Python?

I have a bit-string of 32 characters that I need to represent as hexadecimal in Python. For example, the string "10000011101000011010100010010111" needs to also be output as "83A1A897".
Any suggestions on how to best go about this in Python?
To format to hexadecimal you can use the hex function:
>>> hex(int('10000011101000011010100010010111', 2))
0x83a1a897
Or to get it in exactly the format you requested:
>>> '%08X' % int('10000011101000011010100010010111', 2)
83A1A897
>>> binary = '10010111'
>>> int(binary,2)
151
>>> hex(int(binary,2))
'0x97'
I hope this helps!
You can do this very easy with build in functions.
The first thing you want to do is convert your binary to an integer:
>> int("1010",2)
10
The second step then would be to represent this as hex:
>> "%04X" % int("1010",2)
'000A'
in case you don't want any predefined length of the hex string then just use:
>> "%X" % int("1010",2)
'A'
>> "0x%X" % int("1010",2)
'0xA'
To read in a number in any base use the builtin int function with the optional second parameter specifying the base (in this case 2).
To convert a number to a string of its hexadecimal form just use the hex function.
>>> number=int("10000011101000011010100010010111",2)
>>> print hex(number)
0x83a1a897L
Well we could string format just like Mark Byers said.Or in other way we could string format in another method like given below:
>>> print('{0:x}'.format(0b10000011101000011010100010010111))
83a1a897
To make the alphabets between the hex in upper case try this:
>>> print('{0:X}'.format(0b10000011101000011010100010010111))
83A1A897
Hope this is helpful.

Categories