Skip to content

Instantly share code, notes, and snippets.

@spencer-p
Created June 7, 2020 03:51
Show Gist options
  • Save spencer-p/7b1dc7a58b0f19c5da39bd686b4ca219 to your computer and use it in GitHub Desktop.
Save spencer-p/7b1dc7a58b0f19c5da39bd686b4ca219 to your computer and use it in GitHub Desktop.
/*
* basechange.c
* This is a simple tool to display a number (from any base) in decimal, hexadecimal, octal, and binary.
*/
#include <stdio.h>
#include <stdlib.h>
void print_all_bases(int n);
void print_bits(int n);
int main(int argc, char **argv) {
int base = 0;
// Read the number we got
if (argc < 2) {
printf("%s <number> [base]\n", argv[0]);
return 1;
}
// Read the base we got, if we did
if (argc >= 3) {
base = atoi(argv[2]);
}
// Parse the number we got and print it in other bases
// Note strtol can detect hex and octal, and accepts 0 as a base
// (unspecified base). NULL lets it read the whole string.
print_all_bases(strtol(argv[1], NULL, base));
return 0;
}
void print_all_bases(int n) {
printf("Dec:\t%d\nHex:\t0x%X\nOctal:\t0%o\n", n, n, n, n);
printf("Binary:\t0b");
print_bits(n);
putchar('\n');
}
void print_bits(int n) {
if (n > 0) {
print_bits(n/2);
putchar(n%2==0?'0':'1');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment