不使用标准库的十六进制C代码

时间:2011-02-11 06:10:43

标签: c

我想编写C代码,它将第一个字符串转换为整数,然后将整数转换为十六进制。 例如:我有Ip iddress为“172.24.18.240”现在首先找到它的第一个点并取出它之前的数字“172”将其转换为整数然后转换为inti十六进制它应该对所有像24这样做,18,240并转换为长整数值

感谢任何帮助。

4 个答案:

答案 0 :(得分:0)

也许是这样的?

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++;
}

答案 1 :(得分:0)

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;
}

十六进制值将存储在hexString

答案 2 :(得分:0)

#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
}

答案 3 :(得分:-1)

    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');

或多或少难看,但应该在IP地址上工作。