-1

After checking out this question I did not found required solution, so I've tried to use strtol in following manner:

in = (unsigned char *)malloc(16);

for(size_t i = 0; i < (size_t)strlen(argv[2]) / 2; i+=2 )
{
    long tmp = 0;
    tmp = strtol((const char *)argv[2] + i, &argv[2] + 2, 16);
    memcpy(&in[i], &tmp, 1);
}

This code produced several intermediate values:

Watches of local variables

Can someone please explain me why entire in array gets filled by 0xFF(255) bytes and why tmp is not equal it's estimated value?

Tips about how to improve above code to fill in array with correct hex values also welcome.

Community
  • 1
  • 1
im_infamous
  • 327
  • 1
  • 3
  • 17
  • 1
    Get rid of the casts. `(unsigned char *)` is unnecessary. `(size_t)` is unnecessary as the return type of `strlen()` already is `size_t`. And `(const char *)argv[2] + i, &argv[2] + 2` is just wrong. – cremno May 07 '16 at 19:45
  • The second argument for `strtol` is quite wrong - nothing to do with the input string. And I suggest your loop should be to `strlen(...)` not `strlen(...)/2`, if you are aiming to try converting the input string several times, skipping the first pair, next pair, etc of hex digits. – Weather Vane May 07 '16 at 19:49

1 Answers1

1

Your code is erroneous for multiple counts and the casts hide the problems:

Casting the return value of malloc is not necessary in C and can potentially hide an unsafe conversion if you forget to include <stdlib.h>:

in = (unsigned char *)malloc(16);

Casting the return value of strlen to (size_t) is useless, even redundant as strlen is defined to return a size_t. Again you might have forgotten to include <string.h>...

for (size_t i = 0; i < (size_t)strlen(argv[2]) / 2; i += 2) {
    long tmp = 0;

strtol takes a const pointer to char, which argv[2] + i will convert to implicitly. The cast (const char*) is useless. The second argument is the address of a char*. You pass the address of the fifth element of argv, in other terms &argv[4], most certainly not what you indent to do, although your loop's purpose is quite obscure...

    tmp = strtol((const char *)argv[2] + i, &argv[2] + 2, 16);

Copying the long value in tmp with memcpy would require to copy sizeof(tmp) bytes. Copying the first byte only has an implementation defined effect, depending on the size of char and the endianness of the target system:

    memcpy(&in[i], &tmp, 1);
}

You should post a complete compilable example that illustrates your problem, a code fragment is missing important context information, such as what header files are included, how variables are defined and what code is executed before the fragment.

As written, your code does not make much sense, trying to interpret its behavior is pointless.

Regarding the question in reference, your code does not even remotely provide a solution for converting a string of hexadecimal characters to an array of bytes.

chqrlie
  • 131,814
  • 10
  • 121
  • 189