4

I have some Matlab code that I am trying to convert to Python.

In Matlab the code takes a string and converts it to a double, then to binary.

x = dec2bin(double(string), 8);

Now, the string has numbers, letters, decimal points, and commas. Matlab has no problems converting this.

Is there anything in Python that can do this?

I've tried using bin(), changing the string to a float first, various Numpy options like:

x = numpy.base_repr(string, 2, 8)

and

numpy.binary_repr()

1 Answer 1

6

You can do it easily with:

>>> string = "foo"
>>> res = [bin(ord(i)) for i in string]
['0b1100110', '0b1101111', '0b1101111']

The same example in matlab gives the same result:

>>> dec2bin(double('foo'), 8)
01100110
01101111
01101111
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.