*((unsigned char *)......)是什么意思?

时间:2015-10-24 20:15:08

标签: c++ pointers


因为我仍然不被允许发表评论,所以我会将此作为一个问题发布 有人曾经发布过这段代码作为答案(它有效,一切都很好),但我真的不知道那段代码是如何工作的。

答案与将字节转换为浮点数有关。

typedef unsigned char uchar;

float bytesToFloatA(uchar b0, uchar b1, uchar b2, uchar b3)
{
    float output;

    *((uchar*)(&output) + 3) = b0;
    *((uchar*)(&output) + 2) = b1;
    *((uchar*)(&output) + 1) = b2;
    *((uchar*)(&output) + 0) = b3;

    return output;
}

我知道浮点数是如何工作的,我知道他正在使用浮点数的地址将字符从第一个到第四个用char位分配。

我不明白的是这部分代码:

*((uchar*) ... )

我真的很感激答案,因为我相信它会让我更好地理解指针和演员!

4 个答案:

答案 0 :(得分:2)

uchar是一个字节 uchar*是指向字节的指针 &output是浮动output的地址 (uchar*)(&output)output作为字节地址的地址 因此,*(uchar*)(&output)output,因为它是uchar

答案 1 :(得分:1)

让我们从一开始就开始:

&output // the address of float variable 'output'

(uchar*)(&output) // take the address of 'output' and treat it 
                  // as it were the address of  unsigned char

(uchar*)(&output) + 3 // add to that address 3*sizeof(unsigned char) bytes
                      // which is 3 bytes

*((uchar*)(&output) + 3) // dereference that address so it becomes
                         // like a 'uchar' variable which lays at the
                         // address which we saw in the previous step

*((uchar*)(&output) + 3) = b0; // assign to it value of 'b0'

答案 2 :(得分:0)

&输出但是获取浮点数的地址。 (uchar *)但是说“将其视为uchar的地址,而不是浮点数。+ x位然后根据uchar的大小计算地址偏移量,而不是浮点数。

总的来说,将此视为'将此地址视为无符号字符(而不是浮点数)的地址,并返回该地址处的字符(上面的uCH数)。

您提供的示例代码实际上并不是一种好的做法 - 它会对浮点数的大小做出某些非可移植的假设。

这种演员的“最佳实践”是“看看你是否可以避免这样做”,如果没有,至少尝试并确保它不会导致未定义的行为(例如通过无效的内存访问)。

答案 3 :(得分:0)

(uchar*)(&output)

此部分将float output的地址转换为uchar

*中的*(...)是取消引用运算符,将结果值分配给uchar b0b1等等。