简体   繁体   English

(unsigned long)1 和 *(unsigned long *) 是什么意思?

[英]What does (unsigned long)1 and *(unsigned long *) mean?

This is a program that prints floating point integers bit representation.这是一个打印浮点整数位表示的程序。 What does *(unsigned long *)a and (unsigned long)1 mean? *(unsigned long *)a(unsigned long)1是什么意思?

#include <stdio.h>

void printBits(void *a){

    int i;
    unsigned long x;
    x = *(unsigned long *)a;
    for (i = 63; i >= 0; i--){
        if ((x & ((unsigned long)1 << i)) != 0)
            printf("1");
        else
            printf("0");
        if (i == 63)
            printf(" ");
        if (i == 62)
            printf(" ");
        if (i == 52)
            printf(" ");
    }
    printf("\n");
}

int main(void){
    
    double x = -145.4;
    printBits(&x);
    return 0;
}

Both are type casts ie explicit type conversions.两者都是类型转换显式类型转换。


In

x = *(unsigned long *)a; 
    ^                
//dereference

(unsigned long *)a casts a to a pointer to unsigned long and then dereferences it to assign its value to the local variable x . (unsigned long *)aa强制转换为指向unsigned long的指针,然后取消引用它以将其值分配给局部变量x


(unsigned long)1

Simply casts 1 to unsigned long which by default would have the type int .只需将1强制转换为unsigned long ,默认情况下其类型为int


The first is needed because you can't dereference a void pointer, the second is there to avoid undefined behavior, see chux - Reinstate Monica's comment .第一个是必需的,因为您不能取消引用void指针,第二个是为了避免未定义的行为,请参阅chux - Reinstate Monica's comment More details here .更多细节在这里

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

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