Binary to unsigned int using bitwise operations and pointer arithmetic in C

半世苍凉 提交于 2019-12-13 05:50:00

问题


I can only use bitwise operations and pointer arithmetic to solve this problem. I am converting from binary to unsigned int.

The function I am writing is:

unsigned int atob(const char* nptr);

atob("101") should return 5, atob("11000") should return 24, atob("11$") should return 3, and atop("") should return 0.

I'm pretty new to bitwise operations, so I really need some help specifically in that area.

edit:

nptr can only be incremented, not other inc/dec's are allowed.


回答1:


unsigned bits2val(char *bits)
{
    unsigned val;

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

    return val;
}



回答2:


Here's my example implementation, using just shifts and ors (assuming you can use ++ for string-manipulation):

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

    // we need to go right to left;
    const char *end = input;
    // make sure we only read '0's and '1's
    while ((*end == '0') || (*end == '1'))
    {
        end++;
    }

    while (--end >= input) {
        // check for overflow
        if ((currentBit >> 3) > sizeof(result))
            break;

        char isCurrentBitSet = *end == '1';
        unsigned setValue = (isCurrentBitSet << currentBit);
        result |= setValue;

        currentBit++;
    }

    return result;
}



回答3:


Start with the basics http://www.wikihow.com/Convert-from-Decimal-to-Binary



来源:https://stackoverflow.com/questions/11310796/binary-to-unsigned-int-using-bitwise-operations-and-pointer-arithmetic-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!