Hex to Decimal conversion [K&R exercise]

后端 未结 8 1972
梦如初夏
梦如初夏 2021-01-02 23:35

I\'m learning C and I can\'t figure out one of the K&R exercises, the listing:

Exercise 2-3, Write the function htoi(s), which conv

8条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-02 23:44

    I'm probably not making a great contribution, there are good answers above. But I'll give it a try.

    As others did before me, I'm leaving some functionality for you to implement.

    int htoi(const char* x)
    {
    
            unsigned int current_position;/*current position is to be defined*/
            int prefixed=0;                                                         
            int dec=0;
            char* y = x;
    
            if (x && x+1 && (*(x+1)=='x' || *(x+1)=='X')){  /*Is 0x or 0X prefix present?*/
                    prefixed= PREFIXED;             
            }
    
            if (prefixed) y+=2; /*Jumps over 0x or 0X*/     
    
    
            while (*y){
                    /*getPos(const char*) and singleHexToDec(const char*,unsigned int) functions to be implemented*/
                    current_position=getPos(y);
                    dec+=singleHexToDec(y,current_position); 
            }
            return dec;
    }
    

提交回复
热议问题