Convert Unsigned Integer to Float

I’m working with a RedLion device that treats integers as signed, and they don’t provide the function needed to convert an unsigned integer into a floating point.   Here is some code that will treat the 32 bit register as an unsigned integer and convert it to a double precision float.

Screenshot from 2016-07-28 14:40:53

//convert 32 bit unsigned integer to a float (returned as a string)
// Sparky Geek, LLC July 2016

// in signed integers, negative numbers are represented by the two's complement of the absolute value
// the task for this program is to undo this situation (just ignore the two's complement format)
// check to see of the MSB (AKA 'sign bit') is set 
// --- if it is, mask the MSB, read as a signed number, then add 2^31

int working;
cstring result;
int mask = 2147483647; //2^31-1, or 1 zero followed by 31 ones

if (uint_in < 0 ) // check to see if MSB is set
 working = uint_in & mask; //bitwise AND to only pay attention to the least significant 31 bits, filter out MSB
 IntToR64(tmp.TagA[0],working); //have to use tag, since we can't create a local array, convert to double precision float
 TextToR64("2147483648",tmp.TagB[0]); //convert 2^31 to double precision float
 AddR64(tmp.TagC[0],tmp.TagB[0],tmp.TagA[0]); //add the value 2^31 back in, since this is what we masked out earlier, store as a double precision float
 IntToR64(tmp.TagC[0],uint_in); // if the MSB was zero, the function will work as it

result = AsTextR64(tmp.TagC[0]); //convert to string to pass back from program

return result;
This entry was posted in Industrial Automation and tagged , , , . Bookmark the permalink.

One Response to Convert Unsigned Integer to Float

  1. Pingback: Convert Allen Bradley Logix 5000 Time to Unix Time (Epoch) | Brian Gallimore's Blog

Comments are closed.