Skip to content

Commit 4d66513

Browse files
authored
Refactor binary to hexadecimal conversion program
Updated the binary to hexadecimal conversion program to read binary as a string for safer input handling and added validation for binary digits.
1 parent e5dad3f commit 4d66513

File tree

1 file changed

+22
-14
lines changed

1 file changed

+22
-14
lines changed
Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,29 @@
1-
/*
2-
* C Program to Convert Binary to Hexadecimal
3-
*/
41
#include <stdio.h>
2+
#include <string.h>
3+
#include <math.h>
54

6-
int main()
5+
int main(void)
76
{
8-
long int binary, hexa = 0, i = 1, remainder;
7+
char binary[65]; // up to 64 bits
8+
long decimal = 0;
9+
int i, len;
910

10-
printf("Enter the binary number: ");
11-
scanf("%ld", &binary);
12-
while (binary != 0)
13-
{
14-
remainder = binary % 10;
15-
hexa = hexa + remainder * i;
16-
i = i * 2;
17-
binary = binary / 10;
11+
printf("Enter a binary number: ");
12+
scanf("%64s", binary); // read as string (safer)
13+
14+
len = strlen(binary);
15+
16+
// Validate and convert binary → decimal
17+
for (i = 0; i < len; i++) {
18+
if (binary[i] != '0' && binary[i] != '1') {
19+
printf("Invalid binary number!\n");
20+
return 1;
21+
}
22+
decimal = decimal * 2 + (binary[i] - '0');
1823
}
19-
printf("The equivalent hexadecimal value: %lX", hexa);
24+
25+
// Print as hexadecimal
26+
printf("Equivalent hexadecimal value: %lX\n", decimal);
27+
2028
return 0;
2129
}

0 commit comments

Comments
 (0)