Вопрос

i have a hex value say for example 0x0a010203 and i want to convert it to a string such that after conversion it should be like "10.1.2.3",How to extract the individual fields from the hex value ?

Это было полезно?

Решение 2

Fill a struct in_addr and use inet_ntoa() ("Internet address to ASCII string"):

#include <arpa/inet.h>

struct in_addr addr;
addr.s_addr = htonl(0x0a010203); // s_addr must be in network byte order 
char *s = inet_ntoa(addr); // --> "10.1.2.3"

Note that the string returned by inet_ntoa() may point to static data that may be overwritten by subsequent calls. That is no problem if it is just printed and then not used anymore. Otherwise it would be necessary to duplicate the string.

Другие советы

You can use bit masking and bit shifts, eg:

unsigned int val = 0x0a010203;
printf("%d.%d.%d.%d",
     (val & 0xFF000000) >> 24,
     (val & 0x00FF0000) >> 16,
     (val & 0x0000FF00) >> 8,
     val & 0x000000FF);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top