Skip to content

Instantly share code, notes, and snippets.

@haseeb-heaven
Created March 3, 2023 23:10
Show Gist options
  • Save haseeb-heaven/dec44be822f5b4a379af85515b03a38f to your computer and use it in GitHub Desktop.
Save haseeb-heaven/dec44be822f5b4a379af85515b03a38f to your computer and use it in GitHub Desktop.
This C program detects the base of an input number and validates it. The program examines the first few characters of the input string to detect the base (binary, octal, decimal, or hexadecimal) and validates the input number to ensure that it contains only valid digits for the detected base
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
bool IsValidNumber(char *p_input, int base);
int DetectBase(char *p_input);
int main() {
char input[100];
int base;
printf("Enter a number: ");
fgets(input, sizeof(input), stdin);
base = DetectBase(input);
input[strcspn(input, "\n")] = '\0'; // Remove newline character
if (base == 8 || base == 16) {
memmove(input, input + 2, strlen(input)); // Remove "0b" or "0x" prefix
}
if (IsValidNumber(input, base)) {
printf("The number %s is valid in base %d\n", input, base);
} else {
printf("The number %s is not valid in base %d\n", input, base);
}
return 0;
}
bool IsValidNumber(char *p_input, int base) {
static const char *base_names[] = {"Binary", "Octal", "Decimal", "Hexadecimal"};
char *p_endPtr = p_input;
while (*p_endPtr != '\0') {
if (!isdigit(*p_endPtr) && toupper(*p_endPtr) < 'A' || toupper(*p_endPtr) >= 'A' + base - 10) {
printf("The number %s is not valid in base %s because of invalid characters found here '%c'\n", p_input, base_names[base / 2 - 1], *p_endPtr);
return false;
}
p_endPtr++;
}
return true;
}
int DetectBase(char *p_input) {
if (strlen(p_input) >= 2 && p_input[0] == '0' && p_input[1] == 'x') {
return 16;
} else if (p_input[0] == '0' && p_input[1] == 'b') {
return 8;
} else {
return 10;
}
}
@haseeb-heaven
Copy link
Author

Binary:

Valid: 1010, 11100011, 0, 0b1010
Invalid: 2, 102, 10A, 0x1010
Octal:

Valid: 52, 123, 07
Invalid: 89, 888, 08A
Decimal:

Valid: 123, 456, 0
Invalid: A, 123A, 12.3, 0x123
Hexadecimal:

Valid: AB, FFFF, 0xFF, 0xABCD
Invalid: GH, 0xGH, 0xFZ, 1010

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment