Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting to binary in MATLAB and Python

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()
like image 838
Michael D Avatar asked Oct 18 '25 11:10

Michael D


1 Answers

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
like image 94
jabaldonedo Avatar answered Oct 20 '25 00:10

jabaldonedo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!