Home convert 2 bytes into small integer
Reply: 1

convert 2 bytes into small integer

user9044066
1#
user9044066 Published in 2018-01-11 22:23:33Z

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;
Rudy Velthuis
2#
Rudy Velthuis Reply to 2018-01-12 08:08:45Z

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;
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.311466 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO