简体   繁体   中英

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;

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM