简体   繁体   English

在C中使用指针进行转换

[英]casting with pointers in C

I'm in an introductory course and I am curious about casting with pointers. 我正在学习入门课程,并且对使用指针进行转换感到好奇。

What would be the difference between: 之间的区别是什么?

*(uint32_t*)(p) 
(uint32_t)(*p)

p is a pointer. p是一个指针。

*(uint32_t*)(p)

Extracts 32 unsigned bits at the memory location. 在内存位置提取32个无符号位。

(uint32_t)(*p)

Extracts p from the memory location in its native type, and cast that type to a 32 bit unsigned int. 从内存位置以其本机类型提取p,并将该类型转换为32位无符号int。

The results will probably be most notable if p is a floating point type. 如果p是浮点类型,则结果可能最显着。 When extracted the first way you can see the resulting bitwise format of a floating point number (sign|mantissa|exponent). 以第一种方式提取时,您可以看到生成的浮点数(符号)的按位格式。 When extracted the second way the number is converted to an integer, probably via some form of truncation. 当以第二种方式提取时,该数字可能会通过某种截断形式转换为整数。

Here's a fun example program: 这是一个有趣的示例程序:

main(){
    float x = 1.25, *xp = &x;
    uint32_t x1 = (uint32_t)(*xp);
    uint32_t x2 = *(uint32_t *)(xp);
    printf("x1 = %x\nx2 = %x\n",x1,x2);
}

and the output: 和输出:

x1 = 1
x2 = 3fa00000

In former, first you are casting p to uint32_t* and then dereferencing it. 在以前的版本中,首先将p强制转换为uint32_t* ,然后对其取消引用。
In latter, first you are dereferencing p and then casting it to uint32_t . 在后者中,首先要取消引用p ,然后将其强制转换为uint32_t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM