Skip to content

Instantly share code, notes, and snippets.

@annidy
Created April 29, 2015 07:24
Show Gist options
  • Save annidy/29aeb9135afb2792f0fc to your computer and use it in GitHub Desktop.
Save annidy/29aeb9135afb2792f0fc to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
void oc_dump(uint8_t *buf, size_t len)
{
int i;
char *c;
c = "0123456789abcdef";
putchar('<');
for(i = 0; i <len; i++) {
if (i%4 == 0 && i != 0) {
putchar(' ');
}
putchar(c[(buf[i]&0xf0)>>4]);
putchar(c[buf[i]&0x0f]);
}
putchar('>');
}
int hex2int(char c) {
if ((c >= '0' && c <= '9')) {
return c - '0';
}
if (c >= 'a' && c <= 'f') {
return c - 'a' + 0xa;
}
if (c >= 'A' && c <= 'F') {
return c - 'A' + 0xa;
}
return -1;
}
uint8_t *oc_read(char *dp, size_t *outlen)
{
int i, bit;
uint8_t *rdp, *rdpp;
while (*dp && *dp++ != '<') {}
i = 0;
rdp = (uint8_t *)malloc(strlen(dp));
rdpp = rdp;
while(*dp && *dp != '>') {
bit = hex2int(*dp);
if (bit >= 0) {
if (i++ == 1) {
*rdpp++ |= bit;
i = 0;
} else {
*rdpp = bit << 4;
}
}
dp++;
}
*outlen = rdpp - rdp;
return rdp;
}
void hexdump(uint8_t *buffer, size_t index, size_t width)
{
size_t i, spacer;
for (i = 0; i < index; i++)
{
printf("%02x ", buffer[i]);
}
for (spacer = index; spacer < width; spacer++)
printf(" ");
printf("| ");
for (i = 0; i < index; i++)
{
if (buffer[i] < 32)
printf(".");
else printf("%c", buffer[i]);
}
printf("\n");
}
void pprint(char *dp)
{
uint8_t *buf, *bufp;
int line;
size_t len;
size_t index;
size_t width;
width = 16;
len = 0;
buf = oc_read(dp, &len);
for (line = 0, bufp = buf; line * width < len; line++, bufp += width) {
if (len > (line + 1) * width) {
hexdump(bufp, width, width);
} else {
hexdump(bufp, len - line * width, width);
}
}
printf("Length: %d\n", len);
free(buf);
}
char line[1024*100];
int main(int argc, char const *argv[])
{
char *buf;
size_t len;
FILE *fp;
if (argc > 1) {
fgets(line, sizeof(line), stdin);
buf = oc_read(line, &len);
fp = fopen(argv[1], "wb");
fwrite(buf, 1, len, fp);
free(buf);
fclose(fp);
} else {
for (;;) {
fgets(line, sizeof(line), stdin);
pprint(line);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment