I am trying to modify the code in this answer
https://stackoverflow.com/a/5403170/3657941
so that I have a function that converts a hex string to ASCII values which are stored in an output buffer.
I tried to use snprintf but I am getting a segmentation fault. In GDB I am getting
st=error reading variable: Cannot access memory at address 0x726f6445>
out=error reading variable: Cannot access memory at address 0x726f6441>
Here is my code:
#include <stdio.h>
#include <string.h>
int hex_to_int(char c)
{
if (c >= 97)
c = c - 32;
int first = c / 16 - 3;
int second = c % 16;
int result = first * 10 + second;
if (result > 9) result--;
return result;
}
int hex_to_ascii(char c, char d){
int high = hex_to_int(c) * 16;
int low = hex_to_int(d);
return high+low;
}
void hs(const char *st, char *out)
{
//const char* st = "6665646F7261";
int length = strlen(st);
int i;
char buf = 0;
int offset = 0;
for(i = 0; i < length; i++){
if(i % 2 != 0){
//printf("%c", hex_to_ascii(buf, st[i]));
offset += snprintf(out + offset, 255 - offset, ":%c", hex_to_ascii(buf, st[i]));
}else{
buf = st[i];
}
}
}
int main(){
char str;
hs("6665646F7261",&str);
printf("%c\n", str);
}
I expect to send the function hs input "6665646F7261" in hex and get back the ASCII values in "fedora".