2012-07-03 53 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