Here is a very simple conversion from a dynamic byte array to a Single:
 
function BytesToSingle(Data: TByteDynArray;
  Position: Integer): Single;
{-------------------------------------------------------------------------
 DESCRIPTION:  Accepts a byte array and returns a Single.
 PARAMETERS:   The byte array and an integer specifying the position in the array to start.
 RETURNS:      Single
-------------------------------------------------------------------------}
const
  DATA_SIZE: Longint = 4;
begin
  if Position <= High(Data) - (DATA_SIZE - 1) then
    Move(Data[Position], result, DATA_SIZE);
end;
 
And a routine to convert from a Single to Bytes:
 
function SingleToBytes(Data: Single): TByteDynArray;
{---------------------------------------------------------------------------
   DESCRIPTION:    Converts the Single to a 4byte array.
   PARAMETERS:     Data           The Single to convert
   RETURNS:        TByteDynArray  The byte values separated into a byte array
---------------------------------------------------------------------------}
const
  DATA_SIZE : LongInt = 4;
begin
  SetLength(result, DATA_SIZE);
  Move(Data, result[0], DATA_SIZE);
end;
The above routine could also easily be adapted to work with an existing byte array and take a pPosition parameter like the first routine.
 
----- Original Message -----
From: Colin/Mina
Sent: Tuesday, August 31, 2004 9:29 PM
Subject: [DUG] RE: [DUG-Offtopic] Byte to Real conversion

Hi,
 
Any ideas please?
 
I am developing an embedded processor controller that needs to continuously communicate data over a link to another. The baud rate is limited to 9600 Bd. The numeric range of each data packet will need to be at least +/ 12 digits. I am concerned that the time taken to send this data may too high if sent as strings of characters and I would like to limit this.
 
My data values could be easily represented within the four bytes of a 'Single' which is the smallest Real type and would give me a range of 1.5 x 10 ^-45 .. 3.4 x 10 ^38. This being the case I could send the data as 4 x char(bytes) + a checksum and terminator.
 
My question is - What is the simplest way of doing the conversion in each direction. I have to deal with two different microprocessors, but the maths libraries I have in the compilers are not too bad. I've had a play but seem to be getting into problems with type casting.  A Pascal demo would be a great help.
 
Regards
 
  Colin
 
 


_______________________________________________
Delphi mailing list
[EMAIL PROTECTED]
http://ns3.123.co.nz/mailman/listinfo/delphi
_______________________________________________
Delphi mailing list
[EMAIL PROTECTED]
http://ns3.123.co.nz/mailman/listinfo/delphi

Reply via email to