[PD] Getting 32 bit floating point number from 4 sequential bytes

Martin Peach chakekatzil at gmail.com
Sat Apr 6 17:27:08 CEST 2019


On Sat, Apr 6, 2019 at 10:54 AM Arda Eden <ardaeden at gmail.com> wrote:

> With this method, I got the compiler warning about breaking the strict
> aliasing rule:
> uint8_t bytes[4] = {12, 34, 56, 78};
> float f = *(float*)bytes;
>
> Yes, modern c doesn't like type punning.


> This is my code, and for now, it is working properly. But I am not sure if
> this is an efficient way or not.
>
> typedef struct _xsensparse
> {
>     t_object x_obj;
>     uint8_t wrd[4];
>     t_float o;
>     t_outlet *f1_out, *f2_out;
> } t_xsensparse;
>
> static void xsensparse_list(t_xsensparse *x, t_symbol *s, int argc, t_atom
> *argv)
> {
>     for(int i=0; i<argc; i++) {
>     x->wrd[i]=(uint8_t)atom_getfloat(argv+3-i);
>     memcpy(&x->o, &x->wrd, 4);
>     }
>     post("%f",  x->o);
>     outlet_float(x->f1_out, x->o);
> }
>
>
I think the memcpy statement should be outside the for loop. As it is, it
operates the first three times uselessly.
Using a union would be a bit more efficient as it doesn't copy any memory.

Martin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puredata.info/pipermail/pd-list/attachments/20190406/a04a5491/attachment.html>


More information about the Pd-list mailing list