Search code examples
cpointershex

How to write standard output in hexadecimal of a pointer address using write()


In a task I need to print the address of a pointer in hexadecimal into the standard output. The issue is that I am only allowed to include unistd.h so no printf is allowed.

I have tried to cast it into a char* but the cast is quite impossible to achieve. So help would be so appreciated in here.

It should print something like that:

000000010a161f40

Solution

  • I've coded a print_pointer function that does the exact same thing as printf("%p",pointer)

    #include <unistd.h>
    
    void print_pointer(const void *p)
    {
        static const char *table = "0123456789abcdef";
       unsigned long long value = (unsigned long long)p;
       // 1 digit = 4 bits
       char buffer[sizeof(void*)*2];
       int i,idx = 0;
       
       while(value)
       {
           int digit = value % 16;
           buffer[idx++] = table[digit];
           
           value /= 16;
       }
       // zero-padding
       for (i=idx;i<sizeof(buffer);i++)
       {
           buffer[i] = '0';
       }
       // reversed print, as division computes lowest digits first
       for (i=sizeof(buffer)-1;i>=0;i--)
       {
           write(1,buffer+i,1); // write 1 char to standard output
       }
       
        
    }
    
    int main()
    {
        const char *data = "foo";
        
        print_pointer(data);
        
        return 0;
    }