Skip to content

Instantly share code, notes, and snippets.

@Gasol
Created June 26, 2011 11:39
Show Gist options
  • Save Gasol/1047542 to your computer and use it in GitHub Desktop.
Save Gasol/1047542 to your computer and use it in GitHub Desktop.
Convert String to Hexidecimal
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* stringToHex(char *str)
{
int len = strlen(str);
char* buf = malloc(len * 2 + 1);
char* ret = buf;
int i;
char msb = 0, lsb = 0;
for (; *str != 0; ++str) {
msb = *str >> 4 & 15;
lsb = *str & 15;
sprintf(buf, "%x", msb);
sprintf(buf + 1, "%x", lsb);
buf += 2;
}
return ret;
}
char htoi(char ch)
{
if (ch >= '0' && ch <= '9') {
return ch - 0x30;
} else if (ch >= 'a' && ch <= 'f') {
return ch - 0x61 + 10;
} else if (ch >= 'A' && ch <= 'F') {
return ch - 0x41 + 10;
}
return -1;
}
char* hexToString(char *hex)
{
size_t len = strlen(hex);
if (len & 1) return NULL;
char *buf = malloc(len / 2 + 1);
char *ret = buf;
int ch = 0, tmp = 0;
int i;
for (i = 0; i < len / 2; i++) {
char msb = hex[i*2];
char lsb = hex[i*2+1];
tmp = htoi(msb);
if (tmp == -1) {
goto clean;
}
ch = tmp << 4;
tmp = htoi(lsb);
if (tmp == -1) {
goto clean;
}
ch |= tmp;
buf[i] = ch;
}
return ret;
clean:
free(buf);
return NULL;
}
int main(int argc, char *argv[])
{
char *ptr = argv[1];
if (ptr == NULL) return 0;
char *hex = stringToHex(ptr);
printf("hex: %s\n", hex);
char *str = hexToString(hex);
printf("str: %s\n", str);
free(hex);
free(str);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment