GeeksforGeeks » Algorithms

write htoi()

(8 posts)
  • Started 1 year ago by rishabh
  • Latest reply from Ravi Biradar

Tags:

  1. rishabh
    guest
    Posted 1 year ago #

    Given a string that contains hexadecimal number, write a function htoi() that returns the equivalent integer calue

  2. Venki
    Moderator
    Posted 1 year ago #

    // Here is one function
    int getValue(char const* hexString, int const radix)
    {
        int         loopIndex;      // Loop iterator
        int         signFlag = 1;   // Keeps track of sign
        signed int  retValue = 0;   // Final value
        int         currentDigit;   // Current digit under process
        int         len = strlen(hexString);    // Lenght of string
    
        // Check for sign
        if(hexString[0] == '-')
        {
            // Advance the base
            hexString++;
            // Remove '-' from count
            len--;
            // Sing is -ve
            signFlag = -1;
        }
    
        // Iterate from left to right
        // Accumulate the weight of each digit upon occurance of next digit
        for(loopIndex = 0; loopIndex < len; loopIndex++)
        {
            currentDigit = toupper(hexString[loopIndex]) - ASCII_ZERO;
    
            // Is the digit between A through F?
            if(currentDigit > 9)
            {
                // Adjust numerical value
                currentDigit -= (ASCII_A - '9');
            }
    
            // Based on Horner's principle
            retValue = retValue * radix + currentDigit;
        }
    
        // Flip the sign, if required
        retValue *= signFlag;
    
        // This is the final value
        return retValue;
    }
    

    call the function in the following way,

    getValue("1011", 2); // Binary string to integer
    getValue("12345", 10); // Decimal string to integer
    getValue("ABCDE", 16); // Hexadecimal string to integer

    Error handling is omitted.

    Could someone please write test cases for the above program?

  3. abc
    guest
    Posted 1 year ago #

    It fails for getValue("D80", 16).
    It returns 3200, hex for which is C80

  4. abc
    guest
    Posted 1 year ago #

    @Venki:

    I changed the way you calculate currentDigit to the following and then the code works:

     char ch = toupper(hexString[loopIndex]);
          if (ch >= '0' && ch <= '9')
            currentDigit = ch - '0';
          else if (ch >= 'A' && ch <= 'F')
            currentDigit = ch - 'A' + 10;
    
  5. Venki
    Moderator
    Posted 1 year ago #

    Thanks @abc.

  6. Sambasiva
    Member
    Posted 1 year ago #

    #include <stdio.h>
    
    #define hex(c) (( c >= '0' && c <= '9') ? c - '0' :  \
                             10 + ((c >= 'A' && c <= 'F') ? c - 'A' : c - 'a'))
    
    int htoi(const char *s) {
    
        char c;
        int res = 0;
    
        int sign  = (*s == '-') ? s++, -1 : 1;
    
        while((c = *s++)) {
            res = res * 16 +  hex(c);
        }
    
        return sign * res;
    }
    
    int main() {
    
        printf("%d\n", htoi("C80"));
    }
    
  7. wgpshashank

    Posted 1 year ago #

    Here is Sweet , Simple & Excellent Version of Program

    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    void htoi(char *);
    int main()
    {
      char *hex="0xFFFF";
      htoi(hex);
      return 0;
    }
    
    void htoi(char *hexstr)
    {
    char c;
    int val=0,i;
    
    int len=strlen(hexstr);
    for(i=0;i<len;i++)
    {
    c=*(hexstr+2); //pointer will points to F in case of 0xFFFF
    
    if(c>='a' && c<='f')
    {
    val=val*16+(c-'a'+10);
    }
    
    else if(c>='A' && c<='F')
    {
    val=val*16+(c-'A'+10);
    }
    
    else
    {
    
    if(c>='0' && c<='9')
    {
    val=val*16+(c-'0');
    }
    
    }
    printf("Val: %d \t ",val);
    hexstr++;
    
    }
    
    printf("\n Val: %d ",val);
    }

    Please Let me know if AnyThing wrong or for any test case its failing..???

  8. Ravi Biradar
    guest
    Posted 3 months ago #

    "Hey your code fails if user enters an invalid number so look at this following code, it holds good "

    #include<stdlib.h>
    int htoi(const char *ptr){
        char c;
        int i,len,value=0;
        if(ptr[0]=='0'&&(ptr[1]=='x'||ptr[1]=='X'))
        {
            //c=*(ptr+2);
            ptr=ptr+2;
            len=strlen(ptr);
            printf("%s\t%d\n",ptr,len);
    
            for(i=0;i<len;i++){
                c=ptr[i];
                if(c>='0'&&c<='9')
                   value=value*16+(c-'0');
                else if(c>='a'&&c<='f')
                     value=value*16+(10+(c-'a'));
                else if(c>='A'&&c<='F')
                     value=value*16+(10+(c-'A'));
                else{
                      printf("invalid number\n");
                      return -1;
                      }
            }
            return value;
        }
        else{
             printf("invalid number\n");
                      return -1;
        }
    }
    void main(){
         char str[10];
         int value=0;
         printf("enter the hex value\n");
         scanf("%s",str);
         if((value=htoi(str))!=-1)
         printf("%u\n",value);
         system("pause");
    }

Reply

You must log in to post.

RSS feed for this topic