The Float Format

<< Click to Display Table of Contents >>

Navigation:  Multi-Protocol MasterOPC Server > Lua 5.1 Reference Manual > Examples and Other Useful Things > Data Conversion >

The Float Format

FLOAT-type numbers are reals of single precision. Such a number occupies 4 bytes (32 bits) in computer memory. A number consists of mantissa, exponent and the sign bit in the following sequence (Wikipedia:Single-precision floating-point format):

preobrazovanie_dannykh.float_format

Below is the formula of calculation of a FLOAT-type number:

y = (-1)^s*2^(exp-127)*(1+fraction/2^23);

Function example

function ToFloat(register)

   local fraction=bit.BitAnd(register,0x7FFFFF); --mask 23 bits - get mantissa

   local exp=bit.BitRshift(register,23); --shift to the right by 23 bits - get exponent

   local exp=bit.BitAnd(exp,0xFF); --mask bits of exponent

   local sign=bit.BitFromData(register,31); --extract the sign bit

   local float=2^(exp-127)*(1+fraction/2^23); --calculate the number

   if sign==true then float=float*(-1); end; --check the sign

   return float;

end

Example of function invocation

val=1042284544;

FloatNumber=ToFloat(val);

If need to perform the reverse conversion - get its 4 bytes from a Float number, you can use the server.SendAndReciveDaByMask function. To do this, use the following code:

--conversion from float to HEX

local HexValueDump={};

function ConvertFloatToHex(val)    

   local sendmask={"float:0123"};            

   HexValueDump={};

   --pseudo-send one value

   server.SendAndReceiveDataByMask(0,1,sendmask,{val},{"byte"},200,"SendCrc","SendCrc");        

   return HexValueDump;

end

--save the value and cancel sending

function SendCrc(SendTable)

   for i=1,table.maxn(SendTable),1 do

       table.insert(HexValueDump,SendTable[i]);

   end                    

   return -1,SendTable;

end

The principle of the code is as follows. The ConverFloatToHex function declares a mask in the sendmask table that specifies the conversion type and byte order. The variable HexValueDump is cleared. Then, in the server.SendAndReceiveDataByMask function, the value is pseudo-sent to the port - the sent value is converted by the function into a set of bytes, after which this set of bytes is sent to the SendCrc function. This function swaps bytes into the target HexValueDump table and returns -1. The SendAndReciveDataByMask function pauses execution upon receiving a negative value and does not send the value. The generated HexValueDump table can be returned to the called code.

Example:

local HexValueDump=ConvertFloatToHex(12.3); --the HexValueDump table will get 4 bytes representing the number 12.3

Similarly, can convert any numbers - float, double, int32, int16.