本文介绍了为国米preting一种类型为另一种正确的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个浮动,我想国米preT为 unsigned int类型对于一些位-twiddling(假设的sizeof(浮点)==的sizeof(INT)现在)。现在有一些工作各种方式,例如:

Say I have a float that I want to interpret as an unsigned int for some bit-twiddling (let's assume sizeof(float) == sizeof(int) for now). Now there are various ways that "work", for example:

float f = 0.5f;
unsigned int u;

u = * (unsigned int*) (&var); /* works in most compilers */

union {
    float f;
    unsigned int u;
} uconv;

uconv.f = f;
u = uconv.u; /* works in most compilers */

现在我不知道通过心脏的标准,但不确定的行为要归功于严格别名规则IIRC第一个是,我听到,后者是不确定的行为了。

Now I don't know the standard by heart, but IIRC the first is undefined behaviour thanks to the strict aliasing rule and I heard that the latter is undefined behaviour too.

那么,什么是正确的,确定的方式间preT一种类型的值,如果它是另一种类型?

So what is the correct, defined way to interpret the value of one type as if it was another type?

请添加到您的回答它是否适用于C89,C90,C99,甚至C11。

Please add to your answer whether it works for C89, C90, C99 or even C11.

推荐答案

在一般情况下,正确的方法是投下变量的地址无效* 的char * 无符号字符* ,因为任何其他指针转换可能会导致不确定的行为(事实上,因为的)。 为int * 浮法* 是不兼容的指针类型。

In general, the correct way is to cast the variable's address to void*, char* or unsigned char*, because any other pointer cast may cause undefined behavior (indeed, because of strict aliasing). int* and float* are incompatible pointer types.

在该的sizeof 这两种类型是一样的,下面的工作:

When the sizeof both types is the same, the following will work:

memcpy(&u, &var, sizeof(int));  // note: implicit conversion to void [const] *

这是你得到的价值显然是实现定义的,因为它取决于如何既 INT 浮动是再$ p $内存psented。

The value that you get is obviously implementation-defined, since it depends on how both int and float are represented in memory.

严格别名已经出现

Strict aliasing has been around since C89.

修改:看来我错了previously有关联盟黑客造成UB。在C11国草案的相关部分:

EDIT: seems I was wrong previously about the union hack causing UB. The relevant part of the C11 draft states:

如果用于读取联合对象的内容的部件是不一样的最后一次使用的部件
  存储在对象中的值,重值presentation对象的适当部分是reinter preTED
  如在如在6.2.6(一个过程有时被称为'类型所描述的新的类型的对象重新presentation
  双关语'')

- Foonote 95 6.5.2.3结构和联合成员

-- Foonote 95 to 6.5.2.3 Structure and union members

这篇关于为国米preting一种类型为另一种正确的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!