ADVERTISEMENT
ADVERTISEMENT

Convert Hexadecimal String to Integer in C programming language.


IncludeHelp 27 May 2016

In this code snippet we will learn how to convert string formatted data into integer using different methods in c programming language.

Code to Convert Hexadecimal String to Integer in C

#include <stdio.h>
#include <string.h>
#include <math.h>

int main()
{
    unsigned char text[]="7AF2";
    int i,length, intValue,digit,p;
    
    length=strlen(text);
    
    intValue=0;
    
    for(i=(length-1),p=0; i>=0; i--,p++){
        if(text[i]>='0' && text[i]<='9'){
            digit=text[i]-0x30;
        }
        else if((text[i]>='A' && text[i]<='F') || (text[i]>='a' && text[i]<='f')){
            switch(text[i])   {
                case 'A': case 'a': digit=10; break;
                case 'B': case 'b': digit=11; break;
                case 'C': case 'c': digit=12; break;
                case 'D': case 'd': digit=13; break;
                case 'E': case 'e': digit=14; break;
                case 'F': case 'f': digit=15; break;
            }
        }
        intValue+= digit*pow(16,p);
    }

    printf("Integer value is: %d\n",intValue);
    return 0;
}
    
    Integer value is: 31474

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.