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=-0.9 required=5.0 tests=BAYES_00,FROM_NUMERIC_TLD autolearn=no autolearn_force=no version=3.4.4 X-Google-Thread: a07f3367d7,fa37ee962bc4b00d X-Google-Attributes: gida07f3367d7,public,usenet X-Google-NewGroupId: yes X-Google-Language: ENGLISH,ASCII-7-bit Path: g2news2.google.com!news1.google.com!npeer02.iad.highwinds-media.com!news.highwinds-media.com!feed-me.highwinds-media.com!news.glorb.com!news2.glorb.com!news-peer-lilac.gradwell.net!not-for-mail From: "Stuart" Newsgroups: comp.lang.ada References: <4a12ffa3$0$2853$ba620e4c@news.skynet.be> Subject: Re: Conversion from floating point to signed 16 bits Date: Wed, 20 May 2009 09:29:56 +0100 X-Priority: 3 X-MSMail-Priority: Normal X-Newsreader: Microsoft Outlook Express 6.00.2900.3138 X-RFC2646: Format=Flowed; Response X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.3350 Message-ID: <4a13baef$1_1@glkas0286.greenlnk.net> X-Original-NNTP-Posting-Host: glkas0286.greenlnk.net NNTP-Posting-Host: 20.133.0.1 X-Trace: 1242808200 news.gradwell.net 516 dnews/20.133.0.1:44127 X-Complaints-To: news-abuse@gradwell.net Xref: g2news2.google.com comp.lang.ada:5953 Date: 2009-05-20T09:29:56+01:00 List-Id: "Olivier Scalbert" wrote in message news:4a12ffa3$0$2853$ba620e4c@news.skynet.be... > Hello, > > My problem: > I need to convert an "analogic" value which can vary from 0.0 to 1.0 into > a "discrete" value which is a signed 16 bits integer. > > My implementation: > ----------------------------- > with Ada.Text_IO; > > procedure convert is > type Analog_Value is digits 10 range 0.0 .. 1.0; > type Signed_16 is range -32768 .. 32767; > type Unsigned_16 is range 0 .. 65535; > > function Cv(Value: Analog_Value) return Signed_16 is > U16: Unsigned_16; > begin > U16 := Unsigned_16(65535.0 * Value); > return Signed_16(U16 - 32768); > end Cv; > > procedure Put(S16: Signed_16) is > begin > Ada.Text_IO.Put_Line(Signed_16'image(S16)); > end put; > begin > Put(Cv(0.00)); -- Must be -32768 > Put(Cv(0.25)); -- Must be -16384 > Put(Cv(0.50)); -- Must be 0 > Put(Cv(0.75)); -- Must be 16383 > Put(Cv(1.00)); -- Must be 32767 > end convert; > ----------------------------- > > My question: > Is there an other way to do this in Ada (Representation ? Other parts of > Ada I do not know ?) Extending your [reasonable] assumptions about the base type of Analog_Value you could dispense with the Unsigned_16 altogether: function Cv(Value: Analog_Value) return Signed_16 is begin return Signed_16(65535.0*Value - 32768.0); end Cv; If you really wanted to you could formally codify the assumptions by declaring a working base, then make Analog_Value a subtype of that: type Working_Base is digits 10 range -32768.0 .. 65535.0; subtype Analog_Value is Working_Base range 0.0 .. 1.0; Regards Stuart