how to print memory bits in c

后端 未结 6 1101
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:54

    ... to print the actual representation (binary ...

    To convert any variable/object to a string that encodes the binary form uses a helper function that converts memory into a "binary" string. This method also handles function pointers. Uses C99 or later.

    #include 
    #include 
    #include 
    
    //                                    .... compound literal .......
    #define VAR_TO_STR_BIN(x) obj_to_bin((char [sizeof(x)*CHAR_BIT + 1]){""}, &(x), sizeof (x))
    
    char *obj_to_bin(char *dest, void *object, size_t osize) {
      const unsigned char *p = (const unsigned char *) object;
      p += osize;
      char *s = dest;
      while (osize-- > 0) {
        p--;
        unsigned i = CHAR_BIT;
        while (i-- > 0) {
          *s++ = ((*p >> i) & 1) + '0';
        }
      }
      *s = '\0';
      return dest;
    }
    
    int main(void) {
      int i = 42;
      double d = 3.1415926535897932384626433832795;
      printf("Sample\ndouble pi:%s\nint 42:%s\n", VAR_TO_STR_BIN(d), VAR_TO_STR_BIN(i) );
      return 0;
    }
    

    Output (Note: depending in endian-ness, results may vary)

    Sample
    double pi:0100000000001001001000011111101101010100010001000010110100011000  
    int 42:00000000000000000000000000101010
    

    This approach is easy to adapt to hexadecimal form.

提交回复
热议问题