Skip to content

Instantly share code, notes, and snippets.

@giorgi568
Created August 3, 2024 21:53
Show Gist options
  • Save giorgi568/2bb6092cf53a00b200f5d7e048efbb11 to your computer and use it in GitHub Desktop.
Save giorgi568/2bb6092cf53a00b200f5d7e048efbb11 to your computer and use it in GitHub Desktop.
the c programming language exercise 2-3. (hex to int)
#include <stdio.h>
#include <ctype.h>
int expo(int x, int y);
int atoi(char c);
int htoi(char s[]);
void main() {
printf("%d\n", htoi("62Fa"));
}
int expo(int x, int y){
int res;
int i;
if(y > 0) {
res = x;
for(i = 1; i < y; ++i){
res = res * x;
}
} else if(y == 0){
res = 1;
}
return res;
}
int atoi(char c){
return c - '0';
}
int htoi(char s[]) {
int tail = 0;
int head = 0;
int res = 0;
while(s[tail] != '\0'){
++tail;
}
while(tail > 0) {
if(isdigit(s[head])){
res = res + (atoi(s[head]) * expo(16, tail-1));
}else if(s[head] >= 65 && s[head] <= 70){
res = res + ((s[head] - 55) * expo(16, tail-1));
}else if(s[head] >= 97 && s[head] <= 102){
res = res + ((s[head] - 87) * expo(16, tail-1));
}
--tail;
++head;
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment