views:

237

answers:

2

I need to convert a C/C++ double to a 64 bit two's complement, where the Radix point is at bit number 19 (inclusive).

This means that for the format I want to convert to

  • 0x0000 0000 0010 0000 is the number 1
  • 0xFFFF FFFF FFF0 0000 is the number -1
  • 0x0000 0000 0000 0001 is 0.95 x 10^-6
  • 0xFFFF FFFF FFFF FFFF is -0.95 x 10^-6

So far I've though about using the modf function from the C standard library, but that doesn't really cover my needs. I've also looked at some type conversion classes in Boost, but I couldn't find the right solution there either. Does anyone know of a library or easy way to do this conversion? Maybe someone more familiar with Boost can point me in the right direction.

If this helps at all, here is some documentation of how doubles are stored.

Edit:

I have a follow up question, this is really for my own interest. What is 'Radix'? Here it's sort of like a decimal point. But, the only other time I've heard the term Radix was when I was learning about the Discrete Fast Fourier Transform. If I remember correctly, the Radix-II method is fast because there are fewer multiplies need to calculate the DFT.

+1  A: 

Multiply by 2^20 and then convert to the integer type you target (probably long long)

AProgrammer
+4  A: 

This should give the results you want:

double d = someValue();
int64_t fixed_point = static_cast<int64_t>(d * (1024*1024));
Steve Jessop
I'd prefer to write "d * 0x100000" as it makes it more obvious where you are placing the radix. Personal taste though.
VoidPointer
Good point. In real life I expect it will be used in more than one place, and should probably be a named constant. But for 44.20 bit fixed point, a hex literal is probably clearer than decimal.
Steve Jessop