Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading