Newsgroups: fj.lang.c
Path: galaxy.trc.rwcp.or.jp!jaist-news!cs.titech!wnoc-tyo-news!scslwide!wsgw!wsservra!sakamoto
From: sakamoto@sm.sony.co.jp (Tomohiko Sakamoto)
Subject: Re: Typecast
Message-ID: <Cpx09u.A2A@wsservra.sm.sony.co.jp>
Sender: news@wsservra.sm.sony.co.jp (Usenet News System)
Nntp-Posting-Host: sak3
Reply-To: sakamoto@sm.sony.co.jp
Organization: Computer Systems Design Dept., BIS, Sony Corporation
References: <DOHZONO.94May16160246@nd102.sdsft.kme.mei.co.jp>
Date: Mon, 16 May 1994 21:41:53 GMT
Lines: 89
Xref: galaxy.trc.rwcp.or.jp fj.lang.c:1442
X-originally-archived-at: http://galaxy.rwcp.or.jp/text/cgi-bin/newsarticle2?ng=fj.lang.c&nb=1442&hd=a
X-reformat-date: Mon, 18 Oct 2004 15:18:22 +0900
X-reformat-comment: Tabs were expanded into 4 column tabstops by the Galaxy's archiver. See http://katsu.watanabe.name/ancientfj/galaxy-format.html for more info.

In article <DOHZONO.94May16160246@nd102.sdsft.kme.mei.co.jp>,
        dohzono@sdsft.kme.mei.co.jp (Kazuo Dohzono) writes:
> 
> #include <stdio.h>
> #include <stdlib.h>
> 
> typedef union {
>   float f;
>   unsigned char s[4];
> } Float;
> 
> /*
>   single precision floting point format.
>   
>   0x10000000            : sign
>   0x7f800000            : exponent
>   0x007fffff            : mantissa
> */
> int
>   ftoi(Float *f)
> {
>   int sign = f->s[0] & 0x80;
>   int expo = ((f->s[0] & 0x7f) << 1) | ((f->s[1] & 0x80) >> 7);
>   int val = ((0x80 | f->s[1]) << 16) | (f->s[2] << 8) | f->s[3];
> 
>   if (sign)
>     return -(val >> (127 + 23 - expo));
>   else if (!expo)
>     return 0;
>   else
>     return val >> (127 + 23 - expo);
> }
> 
> 
> main()
> {
>   Float f;
>   for ( f.f = -10 ; f.f < 10 ; f.f+=0.5 )
>     printf("%lf, %d\n", f.f, ftoi(&f));
> }

    for (f.f = 12345600; f.f < 22345600; f.f += 1000000)
      printf("%f, %d\n", f.f, ftoi(&f));

12345600.000000, 12345600
13345600.000000, 13345600
14345600.000000, 14345600
15345600.000000, 15345600
16345600.000000, 16345600
17345600.000000, 0
18345600.000000, 0
19345600.000000, 0
20345600.000000, 0
21345600.000000, 0

-------------------------------------------------------------------
typedef union {
float f;
#ifdef LITTLE_ENDIAN
struct { unsigned int mantissa:23, exponent:8, sign:1 } s;
#else
struct { unsigned int sign:1, exponent:8, mantissa:23 } s;
#endif
} Float;

int ftoi(Float *f)
{
int e = f->s.exponent;
int v = f->s.mantissa + 0x800000;

if (e == 0)
return 0;
e -= 127 + 23;
if (e < 0)
v >>= -e;
else
v <<=  e;
return f->s.sign ? -v : v;
}

main()
{
Float f;
for (f.f = 12345600; f.f < 22345600; f.f += 1000000)
printf("%f, %d\n", f.f, ftoi(&f));
}

--
T. Sakamoto
