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 ?
Asked
Active
Viewed 1.1k times
2 Answers
5
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);

jkyako
- 616
- 4
- 6
4
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.

Martin R
- 529,903
- 94
- 1,240
- 1,382
-
-
@AthulSukumaran: `inet_ntop` or `getnameinfo`. See https://stackoverflow.com/a/20130662/1187415 for an example. – Martin R Nov 27 '20 at 12:08
-
Thanks @Martin. But for ipv6, in6_addr stores value as unsigned char[16]. inet_ntop expects this as argument. My question was specifically about hex value. Also htonl doesn't seem to work for such large hex. – Athul Sukumaran Nov 27 '20 at 12:18