开发者

C Code for Hexadecimal without using standard libraries

开发者 https://www.devze.com 2023-02-10 01:56 出处:网络
I want to write C Code which converts first string into integer then integer into hexadecimal. e开发者_如何学Gox: I have Ip iddress as \"172.24.18.240\" now first find out first dot from it and take t

I want to write C Code which converts first string into integer then integer into hexadecimal. e开发者_如何学Gox: I have Ip iddress as "172.24.18.240" now first find out first dot from it and take the number before it that is "172" convert it into integer then convert it inti hexadecimal and it should do the same for all like 24,18,240 and convert into long/integer value

any help is appreciated.


#include <stdio.h> // testing
int main(int argc, char** argv) // testing
{
    char* ipString = argc > 1? argv[1] : "172.24.18.240"; // testing
    char* ip = ipString;
    unsigned int hex;

    for( int i = 0; i < 4; i++ ){
        unsigned int n = 0;
        for( char c; (c = *ip) >= '0' && c <= '9'; ip++ )
            n = 10 * n + c - '0';
        hex = (hex << 8) + n;

        if( *ip == '.' ) ip++;
    }

     printf("%08X\n", hex); // testing
     return 0; // testing
}


Maybe something like this?

char sn[4];
char *nid = hexString;

int nip[4];
int xnip[4];
int j = 0;
while (*nid != '\0') {
  int i = 0;
  memset(sn, '\0', sizeof sn);
  while (isdigit(*nid)) {
    sn[i++] = *nid++;
  }
  if (*nid == '.')
    nid++;

  // now sn should be the number part
  nip[j] = your_str_to_int(sn);
  xnip[j] = your_int_to_hex(nip[j]);
  j++;
}


int main(void)
{
    char hexChars[] = "0123456789ABCDEF";
    char ipString[] = "172.24.18.254"; 
    char hexString[9] = "";
    const char* pch = ipString;

    int num = 0;
    int i = 0;
    do
    {
        if (*pch != '.' && *pch != '\0')
        {
            num *= 10;
            num += (*pch - '0');
        }
        else
        {
            hexString[i++] = hexChars[num / 16];
            hexString[i++] = hexChars[num % 16];
            num = 0;
        }
    } while (*pch++);

    return 0;
}

The hex values will stored in hexString.


    int i = 0, sum = 0;
    char ipString[] = "172.24.18.240";
    do
    {
            if (isdigit(ipString[i])) sum = sum * 10 + ipString[i] - '0';
            else
            {       putchar("0123456789ABCDEF"[sum / 16]);
                    putchar("0123456789ABCDEF"[sum % 16]);
                    putchar('.');
                    sum = 0;
            }
    }
    while (ipString[i++] != '\0');

More or less ugly, but should work on IP addresses.

0

精彩评论

暂无评论...
验证码 换一张
取 消