2

I have very basic code to read raw data from array and interpret it as data of different type. The assertion in the code fails, from what it looks like incorrect recasting within ternary operator in C. This is platform specific, compiled for embedded processor (Analog Devices Tiger Sharc 201). Any idea what may be happening here? I'm at the point of contacting Analog Devices, but figured there is always a chance someone extremely smart can figure out what may be wrong.

#include <assert.h>

typedef union {
    unsigned int uint32;
    float float32;
} c_t;

int main( int argc, char *argv[] )
{   
    unsigned int r;

    int data_type;

    //data is a raw array, could be floats or unsigned int
    unsigned int data[] = {470698344};    

    //cast raw data as mixed union type
    c_t mixed = *(c_t*) data;       

    //interpret all data as unsigned integer
    data_type = 1;

    //this is where cast to float takes place, resulting in loss of precision
    r = data_type ? mixed.uint32 : mixed.float32;

    //also fails, with no union, results in same code
    //r = data_type ? *((unsigned int *)data) : *((float *) data);

    //r = 470698336, loss of precision 
    //due to incorrect cast inside ternary conditional statement at line 23?
    assert(r == 470698344);             

    return 0;
}
4

2 回答 2

3

条件表达式的类型是表达式类型和的x ? a : b通用类型。和的常见类型是...... 无论两个操作数中的哪一个被求值,它的值都会被转换为通用类型,这就是条件表达式的值。abuint32_tfloatfloat

您的数字470698344是 29 位长,但您float只能达到 24 位的精度。所以在转换中,精度会丢失。当条件表达式的值赋给 时r,这个不太精确的浮点值被截断为一个整数,与 不同470698344

于 2013-10-17T00:06:36.540 回答
1

在这里找到了一个很好的参考

  • 如果两个表达式属于同一类型,则结果属于该类型。
  • 如果两个表达式都是算术或枚举类型,则执行通常的算术转换(在算术转换中介绍)以将它们转换为通用类型。
  • 如果两个表达式都是指针类型,或者一个是指针类型而另一个是计算结果为 0 的常量表达式,则执行指针转换以将它们转换为通用类型。
  • 如果两个表达式都是引用类型,则执行引用转换以将它们转换为公共类型。
  • 如果两个表达式都是 void 类型,则公共类型是 void 类型。
  • 如果两个表达式都属于给定的类类型,则通用类型是该类类型。

不在前面列表中的第二个和第三个操作数的任何组合都是非法的。结果的类型是普通类型,如果第二个和第三个操作数都是相同的类型并且都是左值,那么它就是一个左值。

于 2013-10-17T00:34:51.957 回答