# CREATE OWN LIBRARY

Back to Programming

### Description

The program is written here to convert a hexadecimal number into its equivalent binary number. The hexadecimal number is first converted into its equivalent decimal number and then the decimal number is then converted into its equivalent binary.

For example, if a hexadecimal number is ${\left(A2\right)}_{16}$

Now, the equivalent decimal number will be calculated by multiplying each digit of the hexadecimal number with the increasing power of 16 (the power will starts from 0 and will increase from right to left).

Therefore, the equivalent decimal number:

${16}^{1}$ + 2×${16}^{0}$

= 10×161 + 2×160

= 160 + 2

${\left(162\right)}_{10}$

Now, this decimal number will be converted into its equivalent binary by dividing it with 2 until the quotient of the division becomes zero and then take the remainders in reversed order.

Therefore, the binary number is ${\left(10100010\right)}_{2}$

### Algorithm

OUTPUT: The equivalent binary number

PROCESS:

Step 1: [Taking the input]

Step 2: [Converting from hexadecimal to binary]

Set d<-0

Set b<-1

Set n<-length of the string stored in a variable ‘hex’

For i=0 to n-1 repeat

If hex[i]≥'a' and hex[i]≤'z' then

Set hex[i]<-hex[i]-32

[End of ‘if’]

[End of ‘for’ loop]

For i=n-1 to 0 step -1 repeat

[if the value is a numeric digit]

If hex[i]≥'0' and hex[i]≤'9' then

Set d<-d+(hex[i]-48)×b

Set b<-b×16

[End of ‘if’]

[If the value is greater equals to 10 and less equals to 15]

else if hex[i]≥'A' and hex[i]≤'F' then

Set d<-d+(hex[i]-55)×b

Set b<-b×16

[End of ‘else if’]

[End of ‘for’ loop]

[converting from decimal to binary]

Set i<-0

While d>0 repeat

Set binary[i]=character of (d mod 2+48)

Set i<-i+1

Set d<-d/2

[End of ‘while’ loop]

Set binary[i]<-'\0'

[printing the binary number]

Reverse the string stored in a variable ‘binary’

Print the string stored in ‘binary’

Step: Stop.

## TIME COMPLEXITY:

for(i=n-1;i>=0;i--)-----------------------------------------O(n)

{

//if the value is a numeric digit

if(hex[i]>='0' && hex[i]<='9')--------------O(1)

{

d=d+(hex[i]-48)*b;

b=b*16;

}

//if the value is greater equals to 10 and

//less equals to 15

else if(hex[i]>='A' && hex[i]<='F')--------O(1)

{

d=d+(hex[i]-55)*b;

b=b*16;

}

}

//converting from decimal to binary

i=0;

while(d>0)-----------------------------------------O(m)

{

binary[i++]=(char)(d%2+48);

d=d/2;

}

The time complexity is O(n+m) where ‘n’ is the number of digits of the hexadecimal number and ‘m’ is the number of digits of the decimal number.

## SPACE COMPLEXITY:

The space complexity is O(1) as it requires a fixed number of memory spaces to execute the program for any given input.