how to print memory bits in c

后端 未结 6 1103
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:45

    @dbush, @Anton, I mixed your codes. It's okay?

    #include 
    #include 
    
    void print_bytes( void *ptr, size_t size ) ;
    
    int main( void )
    {
        int x = 123456 ;
        double y = 3.14 ;
    
        print_bytes( &x, sizeof(x) ) ;
        print_bytes( &y, sizeof(y) ) ;
    
        return 0 ;
    }
    
    void print_bytes( void *ptr, size_t size )
    {
        //char *buf = (char*) ptr;
        unsigned char *p = ptr ;
    
        for( size_t i = 0; i < size; i++ )
        {
            printf( "%02hhX ", p[i] ) ;
        }
        printf( "\n" ) ;
    
        for( size_t i = 0; i < size; i++ )
        {
            for( short j = 7; j >= 0; j-- )
            {
                printf( "%d", ( p[i] >> j ) & 1 ) ;
            }
            printf(" ");
        }
        printf("\n");
    }
    

提交回复
热议问题