Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi double to byte array

Is simple way to convert double value to its bytes representation? I tried using pointers like:

var
  double_v:double;
  address:^double;
....
double_v:=100;
address:=@double_v;

but every my concepts: how to read thise 8 bytes from address, end with "AV".

like image 763
Artik Avatar asked Dec 29 '12 11:12

Artik


3 Answers

Use a variant record

Type
  TDoubleAndBytes = Record
    case boolean of
      false : (dabDouble : Double);
      true  : (dabBytes : Array [0..7] Of Byte);
  end;

Assign the double value to dabDouble and read the bytes through dabBytes

var
  myVar : TDoubleAndBytes;
  i : integer;

begin
  myVar.dabDouble := 100;
  for i:=0 to 7 do write(myVar.dabBytes[i]);
like image 178
alzaimar Avatar answered Oct 02 '22 16:10

alzaimar


In XE3 there are record helpers for simple types, TDoubleHelper.

This works:

var
  d : Double;
  i : Integer;
begin
  d := 100.0;
  for i := 0 to 7 do
    WriteLn(d.Bytes[i]);
end;

In XE2 there is a declaration TDoubleRec, which is an advanced record.

example:

var
  dRec : TDoubleRec;
  i : Integer;
begin
  dRec := 100.0;
  for i := 0 to 7 do
    WriteLn(dRec.Bytes[i]);
end;

Another common option to access the bytes of a double is to use a typecast:

type
  TDoubleAsByteArr = array[0..7] of byte;
var
  d : Double;
  i : Integer;
begin
  d := 100.0;
  for i := 0 to 7 do
    WriteLn(TDoubleAsByteArr(d)[i]);
end;
like image 44
LU RD Avatar answered Oct 02 '22 15:10

LU RD


Two examples for using of "absolute" ...

Used as function

function GetDoubleByte(MyDouble: Double; Index: Byte): Byte;
var
  Bytes: array[0..7] of Byte absolute MyDouble;
begin
  Result := Bytes[Index];
end;



procedure TForm1.Button1Click(Sender: TObject);
var
 MyDouble:Double;
 DoubleBytes:Array[0..7] of Byte absolute MyDouble; // direct local use
begin
  MyDouble := 17.123;
  ShowMessage(IntToStr(DoubleBytes[0])); // local usage

  ShowMessage(IntToStr(GetDoubleByte(MyDouble,0))); // via function call

end;
like image 41
bummi Avatar answered Oct 02 '22 15:10

bummi