tags:

views:

60

answers:

3

I am trying to encode a string in hex8 using c. The script I have right now is:

int hex8 (char str) {
 str = printf("%x", str);
 if(strlen(str) == 1) {
  return printf("%s", "0", str);
 } else {
  return str;
 }
}

In this function, I will need to add a 0 ahead of the string if the length is less than 1. I don't know why I'm getting:

passing argument 1 of 'strlen' makes pointer from integer without a cast

Does anyone know why?

+1  A: 

The parameter str is a char. strlen expects a char const * argument. From the context it would seem you need to change the prototype to char *str.

EDIT: You will also need to change the function return type to char *.

Amardeep
+2  A: 

The second line is a problem:

str = printf("%x", str);

printf outputs text to stdout, and returns an integer representing the number of characters that it output, not the actual value that was printed. You should replace this line with a call to sprintf instead, to load the output into str:

sprintf(str, "%x", str);

You can read about the various standard output functions here: Formatted Output Functions

Note that sprintf returns the number of characters that it stored into str, so you can actually use this to check whether you need to add the 0, instead of using strlen at all, like this:

if (sprintf(str, "%x", str) == 1)
{
...
Chad Birch
Except that `sprintf(str, "%x", str)` will try to store it's results in the location pointed to by `(char *)str`, but `str` is of type `char`.
nategoose
+2  A: 

I don't know exactly what hex8 encoding is, but it looks like you're trying to turn a char into a two-byte hex string? In that case, you don't need anything as complicated as you have there. Just do something like this:

char hexstring[3];
char character = 'f';

sprintf(hexstring, "%02x", character);

After that code fragment, hexstring will be "66". If you have a whole string, something like this should work (assuming you've allocated appropriate memory before calling the function):

void string2hex(char *hex, char *in)
{
    while (*in)
    {
       hex += sprintf(hex, "%02x", *in);
       in++;
    }
}
Carl Norum
I went with "explain the issues he's having with his solution", but I suppose "show him the right way to do it" is good too. :b
Chad Birch
You can easily determine the length of the string you will need to store a string as hex by `size_t hex_str_len = 1+ (2 *strlen(str) );` as long as `str` is a null terminated string.
nategoose