Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double from unsigned int[2]?

Tags:

c

I have a 64-bit number written as two 32-bit unsinged ints: unsigned int[2]. unsigned int[0] is MSB, and unsigned int[1] is LSB. How would I convert it to double?

double d_from_u2(unsigned int*);

like image 968
Danijel Avatar asked Jan 17 '26 22:01

Danijel


1 Answers

memcpy it from your source array to a double object in proper order. E.g. if you want to swap the unsigned parts

unsigned src[2] = { ... };
double dst;
assert(sizeof dst == sizeof src);

memcpy(&dst, &src[1], sizeof(unsigned));
memcpy((unsigned char *) &dst + sizeof(unsigned), &src[0], sizeof(unsigned));

Of course, you can always just reinterpret both source and destination objects as arrays of unsigned char and copy them byte-by-byte in any order you wish

unsigned src[2] = { ... };
double dst;

unsigned char *src_bytes = (unsigned char *) src;
unsigned char *dst_bytes = (unsigned char *) &dst;

assert(sizeof dst == 8 && sizeof src == 8);

dst_bytes[0] = src_bytes[7];
dst_bytes[1] = src_bytes[6];
...
dst_bytes[7] = src_bytes[0];

(The second example is not intended to be equivalent to the first one.)

like image 123
AnT Avatar answered Jan 19 '26 19:01

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!