In: Computer Science
How do I covert a char from a sting that is made up of hex values into a long int, without using istringstream and istring in c++?
Solution:
c++ code
#include<bits/stdc++.h>
using namespace std;
long fun(string s){
long res=16,k=0,ans=0;
for(int i=s.length()-1;i>=0;i--){
//we are traversing string from right to left
if(s[i]>='0'&&s[i]<='9'){
ans+=pow(res,k)*(s[i]-'0');
}
else if(s[i]=='a'||s[i]=='b'||s[i]=='c'||s[i]=='d'||s[i]=='e'||s[i]=='f'){
//ascii value of W = 87 and a in hexadecimal is 10 and
//ascii value of a =97
ans+=pow(res,k)*(s[i]-'W');
}
else if(s[i]=='A'||s[i]=='B'||s[i]=='C'||s[i]=='D'||s[i]=='E'||s[i]=='F'){
//ascii value of char 7 is 55 and
//ascii value of char A is 65
ans+=pow(res,k)*(s[i]-'7');
}
k++;
}
}
int main(){
string s;
cout<<"Enter a hexadecimal string"<<endl;
cin>>s;//taking input
//calling fun function with argument input string
long res=fun(s);
cout<<"long int value is "<<res<<endl;
}
Screenshot of the code and output:
NOTE:
If you are satisfied with my answer please do upvote and if you
have any kind of doubts please post in the comment section. I'll
surely help you there.
Thank You:)