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

标签 c++ pointers


因为我仍然不允许发表评论,所以我会将其作为问题发布。
有人曾经发布过这段代码作为答案(它有效并且一切正常)但我真的不明白这段代码是如何工作的。

答案与将字节转换为 float 有关。

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;
}

我知道 float 是如何工作的,我知道他正在使用 float 的地址分配第一个到第四个字节的字符位。

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

*((uchar*) ... )

非常感谢您的回答,因为我相信它会让我更好地理解指针和转换!

最佳答案

让我们从头开始:

&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'

关于c++ - *((unsigned char*) ... ) 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33322845/

相关文章:

c++ - 导致链接器错误的宏

c++ - 使用旋转矩阵旋转三角形 - 从窗口中消失

C++:如何在堆栈内存中创建一个指向我从中生成它的对象的对象?

function - 通过对象而不是指向它的指针调用带有指针接收器的方法?

c++ - 二叉搜索树实现 C++ 运行时错误

c++ - 在docker中编译不同内核的代码会受到什么影响?

c++ - 数组初始化问题

C 简单数组和指针

c++ - 使用未初始化的指针作为函数参数

objective-c - Objective-C header 中的 C 指针损坏