简体   繁体   中英

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.

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 .

Read this: http://chrishecker.com/images/f/fb/Gdmfp.pdf

If you can grok what that article is telling you, you can derive the algorithm you're looking for. Just remember the bias factor in the exponent and the implicit leading one in the mantissa and the rest should fall into place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM