4

I need to convert a 21 bit signed integer (provided in three 7-bit characters) into a 32 bit signed integer. I'm trying to make the function below work. If I define outval as integer, I get range check on the "outval := outval or $FFF00000" statement. If I change outval to a longword, I get range check on "Val21bit := outval". Range checks occur only when the value is negative.

Other than turning off range checking around the assignment, is there any "proper" way to make this work?

function Val21bit(sx:string):integer;       {Input of 3 character string, Vh, Vm, Vl}
var
  outval : longword; // define as Longword to allow or-ing in high bit
{        valueH : 0scccccc
         valueM : 0bbbbbbb
         valueL : 0aaaaaaa
         int    : ssssssss sssscccc ccbbbbbb baaaaaaa  }

begin
     outval := byte(sx[1]);                             //  00000000 00000000 00000000 0scccccc       highest order first
     outval := (outval shl 7) or ($7F and byte(sx[2])); //  00000000 00000000 00sccccc cbbbbbbb
     outval := (outval shl 7) or ($7F and byte(sx[3])); //  00000000 000scccc ccbbbbbb baaaaaaa
     if (outval and $00100000) <> 0 then                //              ^     if sign bit is high, fill in to left
         outval := outval or $FFF00000;                 //  ssssssss sssscccc ccbbbbbb baaaaaaa
     Val21bit  := outval;
end;
kludg
  • 27,213
  • 5
  • 67
  • 118
tim11g
  • 1,935
  • 5
  • 27
  • 41
  • I tried this code on Delphi 3 and it worked flawlessly without any changes (using outval as "integer"). Is this explicitly an issue with Delphi 7 that it would require a typecast when the need for one doesn't make any logical sense? – Glenn1234 Jul 29 '12 at 19:30
  • See more on Range Checking here: https://stackoverflow.com/questions/10134658/how-to-set-default-compiler-options-for-xe2/75578536#75578536 – Gabriel Feb 27 '23 at 09:39

1 Answers1

9

Yes, just typecast explicitly:

 Val21bit  := Integer(outval);
kludg
  • 27,213
  • 5
  • 67
  • 118
  • Yep - that works perfectly. Since I wasn't getting a type mismatch error, I didn't think of typecast as a solution. – tim11g Jul 29 '12 at 18:57