如何将字符串转换为整数

时间:2018-03-19 20:30:48

标签: c

我有一个存储在字符串中的40位十六进制数字,我必须将它存储在一个名为Int40的结构中,该结构只包含一个指向int的指针。

 typedef struct Int40    
 {    
    // a dynamically allocated array to hold a 40     
    // digit integer, stored in reverse order    
    int  *digits;    
} Int40;    

这就是我试过的

Int40 *parseString(char *str)
{
    Int40 *value = malloc(sizeof(Int40) * MAX40);
    for (int i = 0; i < MAX40; i++)
      {
         value[i] = (int)str[i];
      }
    return value;
}

int main()
{
    Int40 *p;
    p = parseString("0123456789abcdef0123456789abcdef01234567");
    printf("-> %d\n", *p);
}

我知道Int cant包含40位数字,这就是为什么我试图将整数数组中的每个数字存储在字符串中,但我的代码似乎不起作用。 编辑:这个数字还包含字母,因为是十六进制数,我必须得到十六进制数的ascii值才能将它存储在int数组中,我该怎么做?

2 个答案:

答案 0 :(得分:0)

您可能会执行以下操作(请注意,我省略了对参数char*的验证,并假设十六进制字符为小写)

// with if statements:

Int40 *parseString(char *str)
{
    Int40 *value = malloc(sizeof(Int40) * MAX40);
    // save the digits array locally (same memory address as value)
    int* digits = value->digits;
    for (int i = 0; i < MAX40; i++)
    {
         char c = str[i];

         // decimal digits case
         if (c >= '0' && c <= '9') {
             digits[i] = c - '0'; // subtract '0' to get the numberical value of c 
         } else { // hex case
             digits[i] = (c - 'a') + 10; // subtract 'a' to get the numerical value of c as 0 + 10 for hex characters A - F
         }
    }
    return value;
}

替代方案:

// with a switch statements:

Int40 *parseString(char *str)
{
    Int40 *value = malloc(sizeof(Int40) * MAX40);
    // save the digits array locally (same memory address as value)
    int* digits = value->digits;
    for (int i = 0; i < MAX40; i++)
    {
         char c = str[i];
         switch (c) {
         // hex 10 - 15
         case 'a': case 'b': case 'c': 
         case 'd': case 'e': case 'f':
             digits[i] = (c - 'a') + 10;  
             break;
         // hex 0 - 9
         default:
             digits[i] = c - '0';
         }
    }
    return value;
}

答案 1 :(得分:0)

#include <stdio.h>
#include <stdlib.h>
typedef int* hex;
hex parseString(char *str)
{
    hex value = (hex)malloc(sizeof(int)*40);
    for (int i = 0; i < 40; i++)
      {
         value[i] = str[i];
      }
    return value;
}

int main()
{
    hex p;
    p = parseString("0123456789abcdef0123456789abcdef01234567");
    printf("-> %d\n", p[0]);
}

<强> ...

#include <stdio.h>
#include <stdlib.h>
typedef struct Int40 
{

    int* hex; 
}Int40;
Int40 parseString(char *str)
{
    Int40 value;
    value.hex = (int*)malloc(sizeof(int)*40);
    for (int i = 0; i < 40; i++)
      {
         value.hex[i] = str[i];
      }
    return value;
}

int main()
{
    Int40 p;
    p = parseString("0123456789abcdef0123456789abcdef01234567");
    printf("-> %d\n", p.hex[0]);
}