Skip to content

Instantly share code, notes, and snippets.

@allada
Last active November 7, 2016 01:55
Show Gist options
  • Save allada/5c6f35e281031f6e0c9a3021e06cecd1 to your computer and use it in GitHub Desktop.
Save allada/5c6f35e281031f6e0c9a3021e06cecd1 to your computer and use it in GitHub Desktop.
#include <string>
int base16Pows[] = {
0x1,
0x10,
0x100,
0x1000,
0x10000
};
inline int convertFromHex(char hex, int position)
{
int offset;
if (hex >= '0' && hex <= '9') {
offset = '0';
} else if (hex >= 'a' && hex <= 'f') {
offset = 'a' - 10;
} else if (hex >= 'A' && hex <= 'F') {
offset = 'A' - 10;
} else {
return -1;
}
return (hex - offset) * base16Pows[position];
}
inline void reportFailed(int position, std::string reason)
{
fprintf(stderr, "Failed at position %d\n", position);
fprintf(stderr, "Reason: %s\n", reason.c_str());
}
int main()
{
std::string ipString = "2001:0db8:0000:0000:0000:ff00:0042:8329";
uint16_t ip[8] = {0};
int ipPart = 7;
int subPosition = 0;
int sum = 0;
for (int i = ipString.size() - 1; i >= 0; i--) {
if (ipPart < 0) {
reportFailed(i, "More than 8 sets");
return 0;
}
if (ipString[i] == ':') {
ip[ipPart] = sum;
sum = 0;
ipPart--;
subPosition = 0;
} else {
int number = convertFromHex(ipString[i], subPosition);
if (number == -1) {
reportFailed(i, "Not Hex");
return 0;
}
sum += number;
if (sum > 0xFFFF) {
reportFailed(i, "Hex too big");
return 0;
}
subPosition++;
}
}
ip[ipPart] = sum;
fprintf(stdout, "Got number %x:%x:%x:%x:%x:%x:%x:%x\n", ip[0], ip[1], ip[2], ip[3], ip[4], ip[5], ip[6], ip[7]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment