Skip to content

Instantly share code, notes, and snippets.

@yokawasa
Created November 21, 2018 03:14
Show Gist options
  • Save yokawasa/477245d0bd092bd060cf20230d9a8bc7 to your computer and use it in GitHub Desktop.
Save yokawasa/477245d0bd092bd060cf20230d9a8bc7 to your computer and use it in GitHub Desktop.
bin2hex command in C language
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// $ cat Makefile
// ----------------------------------------
// all: bin2hex
// su:
// gcc -O3 -o bin2hex bin2hex.c
// clean:
// rm bin2hex
// ----------------------------------------
// $ make
int main(int argc, char **argv) {
if (argc<2) {
printf("Usage: %s <id>\n", argv[0]);
return 1;
}
static char hexconvtab[] = "0123456789abcdef";
const char* old = argv[1];
const size_t oldlen = strlen(old);
char hexed[oldlen * 3 + 1] ;
memset(hexed, '\0', sizeof(hexed));
size_t i, j;
for(i=j=0; i<oldlen; i++) {
hexed[j++] = hexconvtab[old[i]>>4];
hexed[j++] = hexconvtab[old[i]&15];
}
hexed[j] = '\0';
printf("hexed str=%s\n", hexed);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment