how to print memory bits in c

后端 未结 6 1125
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:40

    #include 
    #include 
    
    void print_bits ( void* buf, size_t size_in_bytes )
    {
        char* ptr = (char*)buf;
    
        for (size_t i = 0; i < size_in_bytes; i++) {
            for (short j = 7; j >= 0; j--) {
                printf("%d", (ptr[i] >> j) & 1);
            }
            printf(" ");
        }
        printf("\n");
    }
    
    int main ( void )
    {
        size_t n;
        scanf("%d", &n);
        print_bits(&n, sizeof(n));
        return 0;
    }
    

    This prints bits of the specified object (n here) with the specified size (in bytes).

提交回复
热议问题