how to print memory bits in c

后端 未结 6 1122
Happy的楠姐
Happy的楠姐 2020-11-27 07:21

I\'m learning how numbers are represented in memory. I want to know how to print the actual representation (binary or hexadecimal) in memory of some int and float variables.

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 07:49

    Call print_bits(memory address of variable, size of variable in byte).

    void print_bits(void *ptr, int size) //ptr = memory address of variable, size = size of variable in byte
    {
        long long *ch = ptr;
        int size_bits = size * 8;
        for(int i = size_bits-1; i>=0; i--){
            printf("%lld", *ch >> i & 1) ;
        }
    }
    

    It has been tested successfully, working with any variable of less than or equal to 64 bits. This will probably work correctly with variables with other sizes (Not Tested).

    Calling:

    double d = -7.92282286274e+28;
    print_bits(&d, sizeof(d));
    

    Output:

    1100010111110000000000000000000011100000000000000000000100010111
    

提交回复
热议问题