2012-07-03 142 views
1

好吧,我有一个很好的方式完成的代码,并使用增量++和减量 - 运算符。如何避免使用++和 - 运营商

unsigned int atob(const char* input) 
{ 

    int i = 0; 

    while (input[i] == '0' || input[i] == '1') i++; 

    unsigned result = 0; 
    unsigned currentBit = --i; 

    while ((*input == '0') || (*input == '1')) { 
     char isCurrentBitSet = *input == '1'; 
     unsigned setValue = (isCurrentBitSet << currentBit--); 
     result |= setValue; 
     input++; 
    } 

    return result; 
} 

现在,我需要摆脱所有的DEC( - )/ INC(++),除了输入++在while语句的底部。我对如何执行这个实现感到困惑。

+2

你需要摆脱增量和减量的原因是什么? – EvilTeach

+4

@EvilTeach:我只是在猜测,但我会说这是他的老师(教授,无论如何)间接试图推动他考虑不同的解决方案。 –

+0

有点接近。我只是为了学习而努力! – Jordan

回答

4

在这里你去:

unsigned int atob(const char* input) 
{ 
    unsigned result = 0; 

    while ((*input == '0') || (*input == '1')) { 
    result = (result << 1) | (*input++ - '0'); 
    } 

    return result; 
} 

节省一些堆栈空间太:)

2

通常的方法是以结果集为0开始。然后对于每个输入字符,将结果左移一位,当前位为or,然后重复,直到到达输入字符串的末尾(或无论如何,除了01以外)。

0

将i ++替换为i = i + 1?这似乎很容易。

+0

根本不能使用算术。所以不行。 – Jordan

+1

你的问题应该包括那个陈述? (提示) – Jake1164

1

决定彻底改变我的解决方案:

unsigned int atob(const char* input) 
{ 
    unsigned val; 

    for (val = 0; *input; input++) { 
     if (*input == '1') val = (val << 1) | 1; 
     else if (*input == '0') val <<= 1; 
     else break; 
    } 

    return val; 
} 
+0

像这样的一种你不觉得? http://stackoverflow.com/questions/11310796/binary-to-unsigned-int-using-bitwise-operations-and-pointer-arithmetic-in-c – EvilTeach