Commit 7a229191 authored by Adam Blank's avatar Adam Blank
Browse files

Initial commit

parents
Showing with 124 additions and 0 deletions
+124 -0
#include <stdio.h>
int main() {
int c = 'X';
fread(c, sizeof(char), 1, stdin);
printf("I got: %c\n", c);
}
#include <stdio.h>
int main() {
int c = 'X';
fread(&c, sizeof(char), 1, stdin);
printf("I got: %c\n", c);
}
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <errno.h>
const char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
static inline int to_nibble(char *bin) {
char *endptr = NULL;
char *dup = strndup(bin, 4);
int result = strtol(dup, &endptr, 2);
if (dup + strlen(dup) != endptr) {
free(dup);
return -1;
}
free(dup);
return result;
}
char *pad_to_n(char *str, size_t n) {
size_t len = (strlen(str) / n + 1) * n;
char *out = calloc(len + 1, sizeof(char));
char *ptr = out;
for (size_t i = 0; i < len - strlen(str); i++) {
*ptr = '0';
ptr++;
}
while (*str) {
*ptr = *str;
ptr++;
str++;
}
return out;
}
char *bin_to_hex(char *num) {
char *padded = pad_to_n(num, 8);
char *ptr = padded;
char *end = padded + strlen(padded);
char *out = calloc(strlen(padded) / 4 + 1, sizeof(char));
size_t i = 0;
while (ptr < end) {
int num = to_nibble(ptr);
if (num == -1) {
free(padded);
free(out);
return NULL;
}
out[i] = HEX_DIGITS[num];
ptr += 4;
i++;
}
free(padded);
return out;
}
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
char *readline(char **buf);
char *bin_to_hex(char *num);
static int strip_leading_zeroes(char **ptr) {
int result = 0;
while ((*ptr)[0] == '0' && (*ptr)[1] != '\0') {
(*ptr)++;
result++;
}
return result;
}
static inline void test_case(char *num) {
char *hex = bin_to_hex(num);
if (!hex) {
printf("Invalid input.\n");
return;
}
int leading_zeroes = strip_leading_zeroes(&hex);
printf("hex(0b%s) = 0x%s\n", num, hex);
free(hex - leading_zeroes);
}
int main(int argc, char **argv) {
char *buf = calloc(10000, 1);
while (true) {
printf("Enter a binary number to convert: ");
char *line = readline(&buf);
if (strlen(line) && strcmp(line, "exit") != 0) {
test_case(line);
}
else {
break;
}
}
}
#include <stdio.h>
char *readline(char **buf) {
int charsread = 0;
char c = '\n';
while (fread(&c, sizeof(char), 1, stdin) && c != '\n') {
charsread++;
**buf = c;
(*buf) += 1;
}
return (*buf) - charsread;
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment