c - How to cast a struct of 2 uint into a double -
i have struct below:
struct pts_t { uint32_t lsb; uint32_t msb; };
i cast double. safe of directly write:
pts_t t; double timestamp = t;
and more complex, if struct type part of c dll api, without having "packing" attribute (for compiler) in case have copy pts_t*
receive througth api pts_t instance create control struct packing ?
void f(pts_t* t) { pts_t myt; myt.lsb = t->lsb; myt.msb = t->msb; double timestamp = *(double*)(&myt.lsb); }
the initial thought write following:
double timestamp = *( ( double * ) &( t.lsb ) );
to step through (assuming in 32-bit environment):
- you getting address of identifier
t.lsb
because need find memory address of first byte in structure. note, can alternatively&t
. - you casting memory address pointer double (8 bytes).
- you lastly dereferencing pointer , storing 8 bytes in 8 byte block of memory identifier
timestamp
uses.
remark:
- you need consider little/big endianness.
- you assuming both structure , double aligned (as mentioned below).
- this not portable, assuming double 8 bytes.
now, 3 points in remark blurb lot worry about. becomes big pain when porting code accross multiple platforms. mentioned below, using c unions
better , correct solution portable.
it written follows c unions
:
double timestamp = ( union { double d; struct pts_t pts; } ) { t } .d;
Comments
Post a Comment