I'm on an embedded Linux platform which uses C but also printf
for logging.
I receive data in string
type - "\241\242"
- but they're unprintable characters.
On the sender side, I type in a hex number in string format i.e. "A1A2"
but the sender encodes it as the number 0xA1A2
so on the receiver, I cannot use printf("%s", thing.c_str())
I can use printf("%X")
but only for one character at a time in a for loop printf("%X", thing[i])
. The for-loop would be ok except that since I need to use the logging macro, each hex character comes out on a separate line.
QUESTION
Is there a way to use ONE printf("%X")
to print all the characters in the string as hex?
Something like printf("%X\n", uuid.c_str());
The output of below code.
500E00
A1A2
I think it's printing the pointer from .c_str()
as a hex number.
// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
string uuid = "\241\242";
printf("%X\n", uuid.c_str());
for(int i=0; i < uuid.size(); i )
{
printf("%hhX", uuid[i]);
}
}
CodePudding user response:
Is there a way to use ONE printf("%X") to print all the characters in the string as hex?
No.
Is there a way
You can write your own printf
with your own specifier that will do whatever you want. You might be interested in printk
used in linux kernel for inspiration, I think that would be %*pEn
or %*ph
or %*phN
.
On glibc you can add your own format specifier https://www.gnu.org/software/libc/manual/html_node/Customizing-Printf.html .