简体   繁体   English

从float C ++中提取数字

[英]Extracting digits from a float C++

Given double x , and assuming that it lies in [0,1] . 给定double x ,并假设它位于[0,1] Assume for example that x=0.3 In binary, (keeping 10 digits after the decimal point), it is represented as 假设例如x = 0.3 In binary,(保持小数点后10位),它表示为

x=0.0100110011...

I want to write some C++ code which will extract the 10 digits shown after the decimal point. 我想写一些C ++代码,它将提取小数点后面显示的10位数字。 In other words I want to extract the integer (0100110011)_2. 换句话说,我想提取整数(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. 然后二进制的temp将有必要的10位数。

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. 这样做的原因是,在生成八叉树时,空间中的点根据其名为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. 从理论上讲,这些密钥可以通过将坐标缩放到[0,1],提取比特并交织它们来获得。

Use memcpy to copy double into an array of 32-bit numbers, like this: 使用memcpy将double复制到32位数字的数组中,如下所示:

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. 最多10个有效二进制数字位于b[0]b[1] ,具体取决于您的机器是大端还是小端。

EDIT: The same can be achieved by some casting instead of memcpy, but that would violate strict aliasing rules. 编辑:同样可以通过一些转换而不是memcpy来实现,但这会违反严格的别名规则。 An alternative is to use a union . 另一种方法是使用union

Read this: http://chrishecker.com/images/f/fb/Gdmfp.pdf 请阅读: 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. 只记得指数中的偏差因子和尾数中隐含的前导因子,其余部分应该落到位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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