Mailing List Archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [tlug] Portability of Misaligned Data Access . . . . . . . (was Re: issues with format of double (or IEEE754))



> So, to avoid alignment issues, cajole the rx buffer
> so that result_normal_plus+2 is aligned for a double
> (which is much too tricky), or copy the data into an
> obviously aligned place (much better, no tricks).
>
>    double foo;
>    int i;
>
>    for (i=0;i<sizeof(foo);i++)
>       (*(unsigned char *)&foo)[i]=(*(unsigned char *)(result_normal_plus+2))[i];
>
> or
>
>    double foo;
>    unsigned char *s=(unsigned char *)&foo;
>    unsigned char *t=(unsigned char *)(result_normal_plus+2);
>    int i;
>
>    for (i=0;i<sizeof(foo);i++)
>       *s++=*t++;
>
> then you can access foo without worrying about alignments issues
> (except perhaps for sizeof reporting a padded value
> and reading too much from possibly unpadded (result_normal_plus+2),
> causing a segmentation fault).

In the interest of pedantic portability, C already has a methor for
ensuring that data which must be accessed in different ways is aligned
correctly:

union u
{
  char     as_str[ sizeof( double ) + 1 ];
  struct s
  {
    double as_dbl;
    char   a_null;
  };
};

As confusing as this looks, this should line the double up with the first
'n' bytes of the string and match the sizes of the two representations
on any mahine.

You could get away with:

union u
{
  char   as_str[ sizeof( double ) ];
  double as_dbl;
};

as long as you only write/read the chars as chars and *not* as a string
(since it will be missing it's trailing null char. You definately don't
want to use strcopy to write into this union.

However, we're still making assumptions about the storage format of a
null. Truly portable code would have to worry about things like the order
of the bytes in memory.

None of which brings the program any closer to working.

---
Joseph L (Joe) Larabell            Never fight with a dragon
http://larabell.org                     for thou art crunchy
                                  and goest well with cheese.


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links