-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhexa_to_binary.c
42 lines (39 loc) · 1.11 KB
/
hexa_to_binary.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include "base.h"
/**
* hex_to_bin - This function converts hexadecimal to binary
* @hexa: hexadecimal argument
* Return: Return (0) on success. (-1) for otherwise
*/
int hex_to_bin(const char *hexa)
{
int decimal, power, len;
decimal = 0;
power = 0;
char value;
len = strlen(hexa) - 1; // length of string to use
while(len >= 0) // loop breaks when len is less than 0
{
if (isdigit(hexa[len])) // if its a digit
{
value = hexa[len];
decimal += (value - '0') * pow(16, power); // substract the ascii value of 0(48)
}
if (isalpha(hexa[len]))
{
value = tolower(hexa[len]);
if (value >= 97 && value <= 102)
{
decimal += (value - 'a' + 10) * pow(16, power);
}
else
{
//Handle error
dprintf(2, "Only valid Hexadecimal characters\n");
return (-1);
}
}
len--;
power++;
}
dec_to_bin(decimal); // we call the function that can convert decimal to binary
}