How do you convert an IP address to hexadecimal?

How to convert an IP address into a string in C language?

  • Hi, I found this ip2str() API which converts an IP address into a string. It seems to work fine (see source file and output below). However I do not understand how it works. For example if ip=0x0a080101 then (ip>>24)& 0xff = 0x0000000a right? And the format for the string is %d.%d.%d.%d. So how is the 0x0000000a converted in the character '1' and written in buf[0] plus characted '0' and written in buf[1] for example?? Thanks! typedef uint32 ip_addr_t; static inline char* ip2str(ip_addr_t ip, char *buf) { snprintf (buf, 20, "%d.%d.%d.%d", (ip>>24) & 0xff, (ip>>16) & 0xff, (ip>>8) & 0xff, ip & 0xff); return buf; } int main(int argc, char *argv[]) { ip_addr_t ip; char line_buf[64]; ip = 0x0a080101; ip2str(ip, line_buf); printf("%s\n", line_buf); printf("%c %d %c %d\n", line_buf[0], line_buf[0], line_buf[1], line_buf[1]); return 0; } OUTPUT from program: $ ./ip2string 10.8.1.1 1 49 0 48

  • Answer:

    "So how is the 0x0000000a converted in the character '1' and written in buf[0] plus characted '0' and written in buf[1] for example?? " Well you asked printf() to print a value of 0xa using a %d format (which prints a number in decimal) so of course the result is "10" because that is the decimal representation of 0xa. Is that what you wanted to know or are you asking how printf() itself is implemented?

Fabrizio at Yahoo! Answers Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.