因为我仍然不允许发表评论,所以我会将其作为问题发布。
有人曾经发布过这段代码作为答案(它有效并且一切正常)但我真的不明白这段代码是如何工作的。
答案与将字节转换为 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/