I'm using Python 3.2.2.
I'm looking for a function that converts a binary string, e.g. '0b1010' or '1010', into a binary literal, e.g. 0b1010 (not a string or a decimal integer literal).
It's an easy matter to roll-my-own, but I prefer to use either a standard function or one that is well-established: I don't want to 're-invent the wheel.'
Regardless, I'm happy look at any efficient algorithms y'all might have.
Binary literals can be written in one of the following formats: b'value' , B'value' or 0bvalue , where value is a string composed by 0 and 1 digits. Binary literals are interpreted as binary strings, and are convenient to represent VARBINARY, BINARY or BIT values.
To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .
A binary literal is a number that is represented in 0s and 1s (binary digits). Java allows you to express integral types (byte, short, int, and long) in a binary number system. To specify a binary literal, add the prefix 0b or 0B to the integral value.
The string is a literal.
3>> bin(int('0b1010', 2))
'0b1010'
3>> bin(int('1010', 2))
'0b1010'
3>> 0b1010
10
3>> int('0b1010', 2)
10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With