user9044066
user9044066

Reputation: 137

convert 2 bytes into small integer

I need to generate a small integer data type out of 2 bytes, my code fails with result = 0

function BytestoSmallInt(B0, B1: Byte): SmallInt;
var
  Number: SmallInt;
  pointer : ^SmallInt;
  small: array [0 .. 1] of Byte absolute Number;
begin
  pointer := @Number;
  small[0] := B1;
  small[1] := B0;
  Result := pointer^;
end;

Upvotes: 1

Views: 1131

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596287

I can't reproduce the issue you describe. The code you have shown works fine for me.

However, you don't need the pointer variable at all:

function BytesToSmallInt(B0, B1: Byte): SmallInt;
var
  Number: SmallInt;
  small: array [0 .. 1] of Byte absolute Number;
begin
  small[0] := B1;
  small[1] := B0;
  Result := Number;
end;

And you can even get rid of the array, too:

function BytesToSmallInt(B0, B1: Byte): SmallInt;
begin
  Result := (Smallint(B0) shl 8) or B1;
end;

Upvotes: 5

Related Questions