-1

is there an equivalent of bitconverter.getbytes in Delphi?

https://msdn.microsoft.com/en-us/library/fk3sts66(v=vs.110).aspx

RRUZ
  • 134,889
  • 20
  • 356
  • 483
lakdee
  • 57
  • 1
  • 8

2 Answers2

1

You can use a simple cast. Using the same types as Remy that looks like this:

var
  value: Smallint;
  arr: array[0..SizeOf(Smallint)-1] of Byte;
begin
  value := ...; 
  // by value cast:
  Smallint(arr) := value;
  // or by address cast:
  PSmallint(@arr)^ := value;
end;

or this:

var
  value: Smallint;
  arr: TBytes;
begin
  value := ...; 
  SetLength(arr, SizeOf(value));
  PSmallint(arr)^ := value;
end;
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0

Simply Move() the input variable into a byte array of suitable size, eg:

var
  value: Smallint;
  arr: array[0..SizeOf(Smallint)-1] of Byte;
begin
  value := ...; 
  Move(value, arr[0], SizeOf(value));
end;

Alternatively:

type
  TBytes = array of Byte;

function GetBytes(value: Smallint): TBytes;
begin
  SetLength(Result, SizeOf(value));
  Move(value, Result[0], SizeOf(value));
end;

var
  value: Smallint;
  arr: TBytes;
begin
  value := ...; 
  arr := GetBytes(value);
end;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770