5

I have a 2D array called char **str (allocated by malloc). Lets say str[0] has the string "hello". How would I print that hex?

I tried printf("%d\n", (unsigned char)strtol(str[0], NULL, 16)), but that doesn't print it out in hex.

Any help would be appreciated, thank you!

neby
  • 103
  • 1
  • 2
  • 9
  • 2
    possible duplicate of [Printing hexadecimal characters in C](http://stackoverflow.com/questions/8060170/printing-hexadecimal-characters-in-c) – yelliver Sep 20 '15 at 03:32

2 Answers2

8

You are confused about the fuctionality of strtol. If you have a string that represents a number in hex, you can use strtol like you have:

char s[] = "ff2d";
int n = strtol(s, NULL, 16);
printf("Number: %d\n", n);

When you want to print the characters of a string in hex, use %x format specifier for each character of the string.

char s[] = "Hello";
char* cp = s;
for ( ; *cp != '\0'; ++cp )
{
   printf("%02x", *cp);
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Thanks! But what does the 2 do in `%2x`? If I take it out, it still prints the same hex. – neby Sep 20 '15 at 05:25
  • It means use a width of 2 to print the number. It should really be `%02x` so that it prints a leading zero if the number is less than 16. – R Sahu Sep 20 '15 at 05:27
5

Use %x flag to print hexadecimal integer

example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) 
{
  char *string = "hello", *cursor;
  cursor = string;
  printf("string: %s\nhex: ", string);
  while(*cursor)
  {
    printf("%02x", *cursor);
    ++cursor;
  }
  printf("\n");
  return 0;
}

output

$ ./example 
string: hello
hex: 68656c6c6f

reference

amdixon
  • 3,814
  • 8
  • 25
  • 34
  • Thank you as well! The links really helped and always nice to see different ways to do the same thing. Also, the same question above what does the 02 do in `%02x`? – neby Sep 20 '15 at 05:26
  • 02 is just zeropadding so in the event the hexadecimal integer was less than 2 bytes long eg. 9 then it would print 09.. not really required for the alpha characters as these are all in the two byte hexadecimal range – amdixon Sep 20 '15 at 05:31
  • 1
    Can you explain the *cursor* thing? Also, this will give you compiler error unless you change `*string` to `string[]`. – not2qubit Jul 10 '19 at 08:54