A String -> Hex -> Long -> Hex -> String Converter
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
unsigned char tmpByte[20];
char * hex2str(char *HEXStr) {
int i, n;
for (i = 0; i < strlen(HEXStr)/2; i++) {
sscanf(HEXStr+2*i, "%2X", &n);
tmpByte[i] = (char)n;
}
tmpByte[strlen(HEXStr)/2]=0;
return tmpByte;
}
int back(long dec) {
char hexstr[44];
sprintf(hexstr, "%lx", dec);
printf("%s\n",hexstr);
printf("%s\n",hex2str(hexstr));
return 0;
}
int main(void){
char word[20], hexword[40];
int i, len;
long word_as_l;
printf("Enter The words to convert:\n");
fgets(word, sizeof(word), stdin);
len = strlen(word);
if (word[len-1]=='\n') word[--len] = '\0'; /*To be safe*/
printf(" The length of the word is %i\n", len);
for (i = 0; i<len; i++) {
sprintf(hexword+i*2, "%02x", word[i]);
}
printf("%s\n", hexword);
printf(" The length of the hexword is %i\n", strlen(hexword));
word_as_l=strtol(hexword ,NULL, 16);
printf(" The long\n%ld\n",word_as_l);
printf("********Now Back********\n");
back(word_as_l);
return 0;
}
Three Runs:
[siegelj@tc-login bigInt]$ str2long2str
Enter The words to convert:
hello
The length of the word is 5
68656c6c6f
The length of the hexword is 10
The long
448378203247
********Now Back********
68656c6c6f
hello
[siegelj@tc-login bigInt]$ str2long2str
Enter The words to convert:
good day
The length of the word is 8
676f6f6420646179
The length of the hexword is 16
The long
7453298384152322425
********Now Back********
676f6f6420646179
good day
***********String is too long in the next run*************
[siegelj@tc-login bigInt]$ str2long2str
Enter The words to convert:
good week
The length of the word is 9
676f6f64207765656b
The length of the hexword is 18
The long
9223372036854775807
********Now Back********
7fffffffffffffff
¦¦¦¦¦¦¦
[siegelj@tc-login bigInt]$