Search code examples
delphidelphi-7

How to copy float data into byte array with Delphi?


I'm doing a project with Delphi. There is a function I want to write. I need to put a float data in a byte array (TArray). The c # codes of this function are as follows.

public void SetCalibrationValue(byte channel, float value)
        {
            if (!serialPort.IsOpen)
                return;

            byte[] b = new byte[] {0x7E, 0x0B, 0x04, 0x01, 0x05, channel, 0x00, 0x00, 0x00, 0x00, 0x00};
            Array.Copy(BitConverter.GetBytes(value), 0, b, 0x07, sizeof(float));

            serialPort.Write(b, 0, b.Length);

            if (OnDataTransmit != null)
                OnDataTransmit(new DataTransmitEventArgs(b));
        }

I want to do this code with delphi. I've done it so far, but I couldn't continue. This is my code:

procedure PListenerx.SetCalibrationValue (channel:Byte;value:single);
var
     b:TArray<Byte>;
     c:TArray<Byte>;
begin
     //Comport kapalıysa kontrolü yapılacak
     b[0]:=$7E;
     b[1]:=$0B;
     b[2]:=$04;
     b[3]:=$01;
     b[4]:=$05;
     b[5]:=channel;
     b[6]:=$00;
     b[7]:=$00;
     b[8]:=$00;
     b[9]:=$00;
     b[10]:=$00;

    

end;

Solution

  • Move(value, b[7], SizeOf(Single));
    

    will fill the end of b array with `value

    Note that there is no generic arrays in Delphi 7, so code will look like

    procedure PListenerx.SetCalibrationValue (channel:Byte;value:single);
    var
         b: array of Byte;
    begin 
         SetLength(b, 11);
         //Comport kapalıysa kontrolü yapılacak
         b[0]:=$7E;
         b[1]:=$0B;
         b[2]:=$04;
         b[3]:=$01;
         b[4]:=$05;
         b[5]:=channel;
         b[6]:=$00;
         //no need to fill array end with junk
    
         Move(value, b[7], SizeOf(Single));
    
         //now send b[] to the port
    end;