'Print character array as hex in C
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!
Solution 1:[1]
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);
}
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |