如何将数字的char []转换为整数?

时间:2011-05-04 02:34:34

标签: c char int

假设我有:

Operand[2][4] = {{"1", "2", "3", "4"},{"5", "6", "7", "8"}};

我有一些名为Operand1_sign和Operand2_sign的比特变量(0:正数和1:负数),假设它们是:

Operand1_sign = 0;
Operand2_sign = 1;

如何将其转换为2个整数并对它们应用某些操作(例如求和)

signed int Operand1, Operand2, Result;

所以最后我可以得到以下内容:

Operand1 = + 1234;
Operand2 = - 5678;
Result = Operand1 + Operand2;

2 个答案:

答案 0 :(得分:1)

我不会回答,而是会给你一个线索:数字1234也可以表示为1 * 1000 + 2*100 + 3*10 + 4*1 - 这是解析数字的关键:)

答案 1 :(得分:0)

我可以建议:

#include <stdio.h>
#include <string.h>

int my_atoi(char* operand, int bufsize, int sign)
{
    char* value = new char[bufsize+1];
    memcpy(value, operand, bufsize);
    value[bufsize] = '\0';
    int ret = 0;
    sscanf(value, "%d", &ret);
    if (sign < 0)
    {
        ret = -ret;
    }
    delete [] value;
    return ret;
}

void main()
{
    char Operand[2][4] = {{'1', '2', '3', '4'},{'5', '6', '7', '8'}};
    signed int Operand1 = my_atoi(Operand[0], 4, 1);
    signed int Operand2 = my_atoi(Operand[1], 4, -1);
    signed int Result = Operand1 + Operand2;
}

但是,我肯定会建议你把你的字符串作为空终止字符串。在这种情况下,您可以跳过my_atoi的手动实现,只需执行:

#include <stdlib.h>

void main()
{
    char Operand[2][5] = {{'1', '2', '3', '4', '\0'},{'5', '6', '7', '8', '\0'}};
    signed int Operand1 = atoi(Operand[0]);
    signed int Operand2 = -atoi(Operand[1]);
    signed int Result = Operand1 + Operand2;
}