how to print memory bits in c

后端 未结 6 1106
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:31

    You would need to assign a pointer to the variable in question to a char *, and treat it as an array of bytes of length sizeof(variable). Then you can print each byte in hex using the %X format specifier to printf.

    You can define a function like this:

    void print_bytes(void *ptr, int size) 
    {
        unsigned char *p = ptr;
        int i;
        for (i=0; i

    And call it like this:

    int x = 123456;
    double y = 3.14;
    print_bytes(&x, sizeof(x));
    print_bytes(&y, sizeof(y));
    

提交回复
热议问题