From 4d66513eab23af6e8a33637f840126c5be110b1e Mon Sep 17 00:00:00 2001 From: prem-2006 Date: Fri, 31 Oct 2025 22:10:51 +0530 Subject: [PATCH] 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. --- conversions/binary_to_hexadecimal.c | 36 ++++++++++++++++++----------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/conversions/binary_to_hexadecimal.c b/conversions/binary_to_hexadecimal.c index 4235a07b30..7aa87f3834 100644 --- a/conversions/binary_to_hexadecimal.c +++ b/conversions/binary_to_hexadecimal.c @@ -1,21 +1,29 @@ -/* - * C Program to Convert Binary to Hexadecimal - */ #include +#include +#include -int main() +int main(void) { - long int binary, hexa = 0, i = 1, remainder; + char binary[65]; // up to 64 bits + long decimal = 0; + int i, len; - printf("Enter the binary number: "); - scanf("%ld", &binary); - while (binary != 0) - { - remainder = binary % 10; - hexa = hexa + remainder * i; - i = i * 2; - binary = binary / 10; + printf("Enter a binary number: "); + scanf("%64s", binary); // read as string (safer) + + len = strlen(binary); + + // Validate and convert binary → decimal + for (i = 0; i < len; i++) { + if (binary[i] != '0' && binary[i] != '1') { + printf("Invalid binary number!\n"); + return 1; + } + decimal = decimal * 2 + (binary[i] - '0'); } - printf("The equivalent hexadecimal value: %lX", hexa); + + // Print as hexadecimal + printf("Equivalent hexadecimal value: %lX\n", decimal); + return 0; }