I will briefly explain what I want to do and help appreciated.
I have a hex number which is formatted as 16 byte number like this:
1: std::string myhex = "00000000000000000000000000000FFD";
Then I want to convert it to int. Which I think I successfully do using this:
// convert hex to int
unsigned int x = strtoul(myhex.c_str(), NULL, 16);
printf("x = %d\n", x); // prints 4093 as needed
Now, I want to convert this integer back to hex. Which I think I also successfully do using this:
// Convert int back to hex
char buff[50];
string hexval;
sprintf(buff,"%x",x);
hexval = buff;
cout << hexval.c_str(); // prints "ffd".
But my problem is that now, I want to convert the "ffd" string as above back to the format it was before, eg, 16 byte number padded with zeros like this:
00000000000000000000000000000FFD
I want to convert the string not only print it.
Any help how to do this? Also any corrections if anything I was achieving above is wrong or not OK are welcome. Preferably I would like this to compile on Linux also.
Use the 0
flag (prefix) for zero-padding and field width specification in a printf
:
printf("%032X", x);
Use snprintf
to store it in your string:
snprintf(buff, sizeof(buff), "%032X", x);
Or use asprintf
to store it in a newly-allocated string, to be certain that the memory available for the string is sufficient (since it's allocated by asprintf
):
char *as_string = NULL;
asprintf(&as_string, "%032X", x);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.