本文介绍了便携式数据reinter pretation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
欲reinter一种类型的$ P $角数据作为在便携式方式(C99)另一种类型。
我的不的谈论铸造,我要的 reinter pretation 的某些给定的数据。
此外,通过的移动的我的意思是它不会破坏C99规则 - 我做的不的意味reinter pretated值是在所有系统上平等
我知道3种不同的方式来reinter preT的数据,但只有其中两个是便携式的:
-
这是不可移植的 - 它打破了严格别名规则
/ *#1类型双关* /浮float_value = 3.14;
为int * int_pointer =(INT *)及float_value;
INT int_value = * int_pointer; -
这是依赖于平台,因为它写
浮动后读取来自工会的
进去。但它不会破坏任何C99规则,所以应该工作(如INT
值的sizeof(int)的==的sizeof(浮动)
)。/ *#2联合双关* /联合数据{
浮float_value;
INT int_value;
};联合数据data_value;
data_value.float_value = 3.14;
INT int_value = data_value.int_value; -
应该是罚款,只要
的sizeof(int)的==的sizeof(浮动)
/ *#3 *复制/浮float_value = 3.14;
INT int_value = 0;
的memcpy(安培; int_value,&安培; float_value,sizeof的(int_value));
我的问题:
- 这是正确的?
- 你知道其他方式在移动的办法reinter preT的数据?
解决方案
解决方案2的是的便携 - 通过工会型双关的C99一直是合法的,并且它作出了明确与TC3,它增加下面的脚注部分6.5.2.3:
Annex J still lists it as unspecfied behaviour, which is a known defect and has been corrected with C11, which changed
to
It's not that big a deal as the annex is only informative, not normative.
Keep in mind that you can still end up with undefined behaviour, eg
- by creating a trap representation
- by violating aliasing rules in case of members with pointer type (which should not be converted via type-punning anyway as there need not be a uniform pointer representation)
- if the union members have different sizes - only the bytes of the member last used in a store have specified value; in particular, storing values in a smaller member can also invalidate trailing bytes of a larger member
- if a member contains padding bytes, which always take unspecified values
这篇关于便携式数据reinter pretation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!