String of bits to binary format Python - 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'

Related

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'

convert from string object to binary value 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.

How to convert floating point number in python?

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

Converting from a C double transferred in two hex strings

my very first day with Python.
I like to filter on a trace file generated by C.
Each double from C is formatted in the file by
two hex strings representing 32 bit of the 64 double.
e.g. 1234567890.3 (C double)
inside file:
0xb4933333
0x41d26580
How can I parse and combine it to further work with a Python float?
Thanks in advance
You can use struct, using the 'd' modifier for 'double':
>>> import struct
>>> num1 = '0xb4933333'
>>> num2 = '0x41d26580'
>>> struct.unpack('!d', (num2[2:]+num1[2:]).decode('hex'))[0]
1234567890.3
Be careful what order you append the doubles in, the above assumes a big-endian machine. Also, I stripped 0x as the decode function doesn't expect it.
edit: If you're using Python 3, you need to use bytes.fromhex instead of ''.decode('hex').
Just to give an alternative (the above is a very nice solution):
>>> import struct
>>> num1 = '0xb4933333'
>>> num2 = '0x41d26580'
>>> low_word = int(num1, 16)
>>> high_word = int(num2, 16)
>>> representation = struct.pack('>II', high_word, low_word)
>>> result = struct.unpack('>d', representation)
>>> result[0]
1234567890.3
Here is a the IEEE standard for floating points and how it is created:
http://www.psc.edu/general/software/packages/ieee/ieee.php

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