Note that there are some explanatory texts on larger screens.

plurals
  1. POSingle precision big endian float values to Python's float (double precision, big endian)
    primarykey
    data
    text
    <p>I need to receive hex encoded single precision big endian float values coming from an Arduino over a serial line (RS-232). How do convert them to Python's float which are big endians with double precision?</p> <p>The Arduino send something like "8192323E" and in Python I would like to have 0.174387. I found "<a href="https://stackoverflow.com/questions/1592158/python-convert-hex-to-float">Convert hex to float</a>" but it seems that all of them don't work for single precision floats.</p> <p>From the linked page, this looks promising:</p> <pre><code>from ctypes import * def convert(s): i = int(s, 16) # convert from hex to a Python int cp = pointer(c_int(i)) # make this into a c integer fp = cast(cp, POINTER(c_float)) # cast the int pointer to a float pointer return fp.contents.value # dereference the pointer, get the float </code></pre> <p>But it still doesn't work with my single precision floats.</p> <p>In Java (<a href="http://en.wikipedia.org/wiki/Processing_%28programming_language%29" rel="nofollow noreferrer">Processing</a>) I've been able to do that:</p> <pre><code>float decodeFloat(String inString) { byte [] inData = new byte[4]; inString = inString.substring(2, 10); // discard the leading "f:" inData[0] = (byte) unhex(inString.substring(0, 2)); inData[1] = (byte) unhex(inString.substring(2, 4)); inData[2] = (byte) unhex(inString.substring(4, 6)); inData[3] = (byte) unhex(inString.substring(6, 8)); int intbits = (inData[3] &lt;&lt; 24) | ((inData[2] &amp; 0xff) &lt;&lt; 16) | ((inData[1] &amp; 0xff) &lt;&lt; 8) | (inData[0] &amp; 0xff); //unhex(inString.substring(0, 8)); return Float.intBitsToFloat(intbits); } </code></pre> <p>For your reference, this is the C code running on the Arduino implementing the hex encoding.</p> <pre><code>void serialFloatPrint(float f) { byte * b = (byte *) &amp;f; Serial.print("f:"); for(int i=0; i&lt;4; i++) { byte b1 = (b[i] &gt;&gt; 4) &amp; 0x0f; byte b2 = (b[i] &amp; 0x0f); char c1 = (b1 &lt; 10) ? ('0' + b1) : 'A' + b1 - 10; char c2 = (b2 &lt; 10) ? ('0' + b2) : 'A' + b2 - 10; Serial.print(c1); Serial.print(c2); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload