From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on polar.synack.me X-Spam-Level: X-Spam-Status: No, score=-1.3 required=5.0 tests=BAYES_00,INVALID_MSGID autolearn=no autolearn_force=no version=3.4.4 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 103376,f71c159449d6e114 X-Google-Attributes: gid103376,public From: eachus@spectre.mitre.org (Robert I. Eachus) Subject: Re: Ada 83 - avoiding unchecked conversions. Date: 1996/11/27 Message-ID: #1/1 X-Deja-AN: 201130346 references: <329C63BC.41C6@lmco.com> organization: The Mitre Corp., Bedford, MA. newsgroups: comp.lang.ada Date: 1996-11-27T00:00:00+00:00 List-Id: In article <329C63BC.41C6@lmco.com> Mary Cronk writes: > we have two 16 bit integers which we need to assemble into a single 32 > bit integer (one is high order, the other low order). We wish to avoid > unchecked conversion if we can. Is there a standard accepted way of > doing this? I could ask why you want to avoid Unchecked_Conversion, since in this case the message of the name is exactly what you apparently want, a conversion that does no checking. But I won't ask. The best way to do this in Ada 95 is to have the low order word declared as a modular type, and the upper word as a 16-bit integer: type Mod16 is mod 2**16; type Int16 is range -2**15..2**15-1; type Int32 is range -2**31..2**31-1; ... function Merge_Halves(High: Int16; Low: Mod16) return Int32 is begin return Int32(High) * 2**16 + Int32(Low); end Merge_Halves; If you are using Ada 83 and want portability, or you have the low order bits in a signed number for some reason: function Merge_Halves(High, Low: Int16) return Int32 is begin if Low >= 0 then return Int32(High) * 2**16 + Int32(Low); else return Int32(High) * 2**16 + (2**16 + Int32(Low)); end if; end Merge_Halves; You may be tempted to write: return Int32(High + 1) * 2**16 + Int32(Low); But that risks overflow, as does just omitting the parentheses. A VERY clever compiler might be able to figure out a way to simplify the expression and still do no range checking, but I'll settle for compilers that replace the multiply with a shift, and only do an overflow check on the final add. -- Robert I. Eachus with Standard_Disclaimer; use Standard_Disclaimer; function Message (Text: in Clever_Ideas) return Better_Ideas is...