Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting digits from a float C++

Given double x, and assuming that it lies in [0,1] . Assume for example that x=0.3 In binary, (keeping 10 digits after the decimal point), it is represented as

x=0.0100110011...

I want to write some C++ code which will extract the 10 digits shown after the decimal point. In other words I want to extract the integer (0100110011)_2.

Now I am quite new to bit shifting and the (naive) solution which I have for the problem is the following

int temp= (int) (x*(1<<10))

Then temp in binary will have the necesary 10 digits.

Is this a safe way to perform the above process? OR are there safer / more correct ways to do this?

Note: I don't want the digits extracted in the form of a character array. I specifically want an integer (OR unsigned integer) for this. The reason for doing this is that in generation of octrees, points in space are given hash keys based on their position named as Morton Keys. These keys are usually stored as integers. After getting the integr keys for all the points they are then sorted. Theoretically these keys can be obtained by scaling the coordinates to [0,1], extracting the bits , and interleaving them.

like image 298
smilingbuddha Avatar asked Nov 14 '22 12:11

smilingbuddha


1 Answers

Use memcpy to copy double into an array of 32-bit numbers, like this:

unsigned int b[2]; // assume int is 32-bits
memcpy(b, &x, 8);

The most 10 significant binary digits are in b[0] or b[1], depending on whether your machine is big- or little-endian.

EDIT: The same can be achieved by some casting instead of memcpy, but that would violate strict aliasing rules. An alternative is to use a union.

like image 150
zvrba Avatar answered Dec 28 '22 01:12

zvrba