Using a union would be a bit more efficient as it doesn't copy any memory.
an optimizing compiler will very likely generate identical assembly. look here, how the call to memcpy is reduced to a single 'movss' instruction: https://godbolt.org/z/n5ueWD
@Arda: shouldn't 'wrd' and 'o' be local variables instead of struct members? or do you need somehow to cache the value for later?
Christof
Gesendet: Samstag, 06. April 2019 um 17:27 Uhr Von: "Martin Peach" chakekatzil@gmail.com An: Pd-List pd-list@lists.iem.at Betreff: Re: [PD] Getting 32 bit floating point number from 4 sequential bytes
On Sat, Apr 6, 2019 at 10:54 AM Arda Eden <ardaeden@gmail.com[mailto:ardaeden@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 _______________________________________________ Pd-list@lists.iem.at mailing list UNSUBSCRIBE and account-management -> https://lists.puredata.info/listinfo/pd-list%5Bhttps://lists.puredata.info/l...]