为什么有人在C中使用这种类型的转换? float的引用被转换为int指针,然后被解除引用 [英] Why would someone use this type of cast in C? The reference of a float is cast to an int pointer and then dereferenced

查看:132
本文介绍了为什么有人在C中使用这种类型的转换? float的引用被转换为int指针,然后被解除引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读关于Carmack的快速反平方根算法,并注意到:

I was reading about Carmack's fast inverse square root algorithm and noticed this:

float x;
// ... //
int i = *(int*)&x;

为什么有人选择使用这种奇怪的类型的转换,而不只是以下?

Why would someone choose to use this weird type of casting instead of just the following?

int i = (int)x;


推荐答案

这不同。

int i =(int)x; 会将 float > int ,这将简单地截断它。

int i = (int) x; will cast float to int, which will simply truncate it.

int i = *(int *)& x; / code>将加载到当前存储在 x 中的相同位。 i 。结果与截断 x 完全不同。

int i = *(int *) &x; will load into i the same bits that are currently stored in x. The result is something totally different from truncating x.

这篇关于为什么有人在C中使用这种类型的转换? float的引用被转换为int指针,然后被解除引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆