문제

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