Skip to content

Instantly share code, notes, and snippets.

@mofosyne
Last active January 8, 2022 17:25
Show Gist options
  • Save mofosyne/06719948277cc57d60ff839ef70f4d6e to your computer and use it in GitHub Desktop.
Save mofosyne/06719948277cc57d60ff839ef70f4d6e to your computer and use it in GitHub Desktop.
minimal ipv4 string print
#include <stdio.h>
void ipv4ToStrbuff(char ipStr[], const unsigned char ipaddr[])
{
// assumes that char *ipStr = "XXX.XXX.XXX.XXX";
const char *nibblesToDigits = "0123456789";
int i = 0;
for (i = 0 ; i < 4 ; i++)
{
const unsigned char h = ipaddr[i];
const unsigned char d0 = (h) % 10;
const unsigned char d1 = ((h - h % 10) % 100) / 10;
const unsigned char d2 = ((h - h % 100) % 1000) / 100;
ipStr[i*4 + 0] = nibblesToDigits[d2];
ipStr[i*4 + 1] = nibblesToDigits[d1];
ipStr[i*4 + 2] = nibblesToDigits[d0];
}
}
int main (void)
{
char ipStrBuff[] = "XXX.XXX.XXX.XXX\n";
unsigned char ip[4] = {33,34,25,245};
ipv4ToStrbuff(ipStrBuff, ip);
printf(ipStrBuff);
return 0;
}
@mofosyne
Copy link
Author

gcc test.c -o test && test
033.034.025.245

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment