2

I am trying to convert a string such as "0x7ffd01767a60" to hexadecimal so I can compare pointers. Not sure if this is the best decision.

I am doing this:

    char *address = "0x7ffd01767a60";

    strtol(address,NULL,16);
    printf("%lp",address);

And I am getting this: 0x7ffd01764120

EDIT: It seems I was printing the string address ignoring the function return. Thanks Jens! and schlenk.

SOLVED! This is what I do

    char *address = "0x7ffd01767a60";
    void *p;
    unsigned long int address_hex = strtol(address,NULL,16);
    p = (void*) address_hex;

    printf("%p",p);

printf prints the same memory address.

deko
  • 463
  • 1
  • 6
  • 17
  • Where do you capture the result of [strtoul](http://linux.die.net/man/3/strtoul)? All you do here is print the pointer to the string `"0x7ffd01767a60"` which is different from the content of the string. – Jens Nov 28 '15 at 00:02
  • What do you expect this to do? `strtoul()` has a return value which you simply ignore. – schlenk Nov 28 '15 at 00:02
  • lol ... now I get it. Thank you. Shall I use a long int? – deko Nov 28 '15 at 00:04
  • @deko: If the answer below satisfies your question, please consider accepting it. – Jens Dec 02 '15 at 04:17
  • @Jens I'm sorry Jens, I am new and forgot. Done. – deko Dec 03 '15 at 04:14

1 Answers1

3

You're printing the address of the string itself while ignoring the result of the strtoul() function call. This should work:

const char *address = "0x7ffd01767a60";

unsigned long int address_hex = strtoul(address, NULL, 16);
// Check for errors in errno
printf("%lx\n", address_hex);

Also, personally I prefer code to be as explicit as possible which is why I passed 16 as the base parameter.

Note: Please read the documentation on the return value, to make sure that you identify errors correctly.

Jens
  • 8,423
  • 9
  • 58
  • 78
  • hey Jens, it won't let me to print that, shouldn't it be %lu instead of %p since it is a long int? using %lu I get: 140733653415520 – deko Nov 28 '15 at 00:15
  • @deko: Correct, my bad. According to the [printf()](http://linux.die.net/man/3/printf) documentation, the type for `%p` is a `void *` pointer type, but `address_hex` is an integer. Using `%lx` would be correct in your case assuming you're looking for a hex printout; `%lu` results in a decimal. (Also, I'd avoid casting the integer to a pointer because you might run into problems on architectures where your pointer width is different from your (long) integer width.) – Jens Nov 28 '15 at 04:47