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):

  1. you getting address of identifier t.lsb because need find memory address of first byte in structure. note, can alternatively &t.
  2. you casting memory address pointer double (8 bytes).
  3. you lastly dereferencing pointer , storing 8 bytes in 8 byte block of memory identifier timestamp uses.

remark:

  1. you need consider little/big endianness.
  2. you assuming both structure , double aligned (as mentioned below).
  3. 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

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -