user2864778
user2864778

Reputation: 333

How to convert 2 bytes to one 16-bit number in Delphi?

So I have 2 bytes, for example: 13, 61

I want to convert them into the 16-bit: 3389

Right now I'm using the function:

function IntPower(const N, k: integer): integer;
var
  i: Integer;
begin
  Result:= (256 * N) + k;
end;

Are there any better way to do this on Delphi?

Upvotes: 2

Views: 3640

Answers (3)

Arnaud Bouchez
Arnaud Bouchez

Reputation: 43023

Your code is just fine.

If N,K and result as defined as cardinal, compiler will in fact use SHL asm opcodes, which in fact is not faster those days than * - MUL is a one-cycle op IIRC.

function IntPower(const N, k: cardinal): cardinal; inline;
begin
  Result:= (256 * N) + k;
end;

Here the main trick is to define inline; which will make the code much faster.

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 612904

That method is fine. You could alternatively use shift operations:

Result := N shl 8 + k;

or

Result := N shl 8 or k;

Either works fine and you should pick whichever you prefer.

Upvotes: 4

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108948

Two alternatives are

function CreateWord(const A, B: byte): word;
begin
  result := word(A) shl 8 or B;
end;

and

function CreateWord(const A, B: byte): word;
var
  WR: WordRec;
begin
  WR.Hi := A;
  WR.Lo := B;
  result := word(WR);
end;

Upvotes: 5

Related Questions