Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert binary string to binary literal

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.

like image 468
Brian Drysdale Avatar asked Aug 22 '13 06:08

Brian Drysdale


People also ask

How do you write binary literals?

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.

How do I convert string to binary in Python?

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) .

What are binary literals?

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.


1 Answers

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
like image 125
Ignacio Vazquez-Abrams Avatar answered Oct 20 '22 15:10

Ignacio Vazquez-Abrams