Skip to content

Instantly share code, notes, and snippets.

@hxmwr
Last active November 14, 2018 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hxmwr/fe82a0c67b53af1c36c166c6bccd6e4c to your computer and use it in GitHub Desktop.
Save hxmwr/fe82a0c67b53af1c36c166c6bccd6e4c to your computer and use it in GitHub Desktop.
Get a number's binary representation and hex representation
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <regex.h>
#define TOTAL_TYPE_PATTERNS 2
enum number_type{
TYPE_INT,
TYPE_FLOAT,
TYPE_INVALID = -1
};
void show_bytes(unsigned char *a, int n)
{
int i = 0;
for (;i<n;i++) {
printf("%.2X ", a[i]);
}
printf("\n");
}
void show_bits(unsigned char *a, int n)
{
int i, j;
unsigned char b;
for (i=0;i<n;i++) {
for (j=0;j<8;j++) {
b = ((((unsigned int)a[i]) <<(24+ j)) >> 31);
printf("%d", b);
}
printf(" ");
}
printf("\n");
}
int reg_match(const char *pattern, const char *target)
{
regex_t rgx;
if (regcomp(&rgx, pattern, REG_EXTENDED | REG_NOSUB | REG_NEWLINE) != 0) {
return -1;
}
int result = regexec(&rgx, target, 0, NULL, 0);
regfree(&rgx);
return result;
}
enum number_type get_type(const char *str)
{
const char *patterns[] = {
"^[0-9]{1,10}$",
"^([0-9]{1,6}\\.[[:digit:]]{1,6}(e-?[0-9]+)?)$"
};
int i;
for (i=0;i<TOTAL_TYPE_PATTERNS;i++) {
if (reg_match(patterns[i], str) == 0) {
return i;
}
}
return -1;
}
int main(int argc, char **argv)
{
long a;
float b;
unsigned char *c;
char *type_names[] = {"int", "float"};
if (argc > 1) {
enum number_type type = get_type(argv[1]);
printf("Number(%s) type is %s\n", argv[1], type_names[type]);
switch (type) {
case TYPE_INT:
a = strtol(argv[1], NULL, 10);
c = (unsigned char *)&a;
break;
case TYPE_FLOAT:
b = strtof(argv[1], NULL);
c = (unsigned char *)&b;
printf("%f\n", b);
break;
case TYPE_INVALID:
printf("No valid number to convert.\n");
return 0;
}
printf("--- BINARY FORM ---\n");
show_bits(c, 4);
printf("--- HEX FORM ---\n");
show_bytes(c, 4);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment