How to cast from hexadecimal to string in C?
You cannot simply 'cast', you will need to use sprintf to do the convertion:
unsigned int hex = 0xABC123FF;
char hexString[256];
sprintf(hexString, "0x%08X", hex);
If you want to 'cast' it to string in order to print it, you can use printf directly:
unsigned int hex = 0xABC123FF;
printf("0x%08X", hex);
You cannot cast from a number to a string in C. You'll have to call a function for that purpose.
Just stumbled over this old thread. Who says one cannot cast hex to string? That's a lie, I can:
unsigned int hex = 0xABC123FF;
char *str = (char*)&hex;
Okay it doesn't make sense printing it as C string (zero terminated), but I casted it ;)
Related
To write into a log file, some pointer list (in C language), i would like to convert my int * into a character array before to write it, in the log file.
I know that to convert a decimal to a char buffer we could use something like below but my values could be higher than 9 and this didn't work for that.
int data = 5;
char cData = data + '0';
Have you any solutions ?
Best Regards.
Well, you can't store a decimal more than 9 in a char. I would recommend you to use a char array to store decimal greater than 9 using sprintf() defined in <stdlib.h> like this.
int data = 224;
char arr[10];
sprintf(arr, "%d", data);
A char can't hold both '1' and '0'. You would need at least two char. This is what the printf family does. printf %d will convert an int to a string that's its decimal representation.
Since you said you want to output the result, printf or fprintf might be the best options. If you want to build the string in an array, snprintf.
How can I convert a hex ip (such as 42477f35), and get it to spit out the correct decimal ip (in the example before, the correct result is 66.71.127.53)?
I'd like it to take the hex ip in as a string, then output the correct result as a string too so I can use it elsewhere in the C code.
I'm not an expert in C, so if any of you can help me out, it'd be appreciated.
This is one possibility:
#include <stdio.h>
int ip_hex_to_dquad(const char *input, char *output, size_t outlen)
{
unsigned int a, b, c, d;
if (sscanf(input, "%2x%2x%2x%2x", &a, &b, &c, &d) != 4)
return -1;
snprintf(output, outlen, "%u.%u.%u.%u", a, b, c, d);
return 0;
}
You could use sscanf to pick the hexadecimal out of the original string as integers and then use sprintf to put them into another string in the proper format.
sscanf(hexipstring, "%2x%2x%2x%2x", &uint0, &uint1, &uint2, &uint3);
sprintf("%u.%u.%u.%u", uint0, uint1, uint2, uint3);
Or something like that. i'm never really sure with scanf, so read through some man pages. The "%2x" should tell scanf to use 2 characters at most and interpret them as a hexadecimal number.
-edit: Caf's code is better since it checks for errors in sscanf and uses snprintf rather than sprintf. More errorproof. Use it instead of mine.
Split the hex ip into octets (two hex digits at a time), and convert each octet to a decimal integer.
My question is how I would go about converting something like:
int i = 0x11111111;
to a character pointer? I tried using the itoa() function but it gave me a floating-point exception.
itoa is non-standard. Stay away.
One possibility is to use sprintf and the proper format specifier for hexa i.e. x and do:
char str[ BIG_ENOUGH + 1 ];
sprintf(str,"%x",value);
However, the problem with this computing the size of the value array. You have to do with some guesses and FAQ 12.21 is a good starting point.
The number of characters required to represent a number in any base b can be approximated by the following formula:
⌈logb(n + 1)⌉
Add a couple more to hold the 0x, if need be, and then your BIG_ENOUGH is ready.
char buffer[20];
Then:
sprintf(buffer, "%x", i);
Or:
itoa(i, buffer, 16);
Character pointer to buffer can be buffer itself (but it is const) or other variable:
char *p = buffer;
Using the sprintf() function to convert an integer to hexadecimal should accomplish your task.
Here is an example:
int i = 0x11111111;
char szHexPrintBuf[10];
int ret_code = 0;
ret_code = sprintf(szHexPrintBuf, "%x", i);
if(0 > ret_code)
{
something-bad-happend();
}
Using the sprintf() function like this -- sprintf(charBuffer, "%x", i);
-- I think will work very well.
Is it possible to represent an unsigned character array as a string?
When I searched for it, I found out that only memset() was able to do this (But character by character).
Assuming that is not the correct way, is there a way to do the conversion?
Context: I am trying to store the output of a cryptographic hash function which happens to be an array of unsigned characters.
eg:
unsigned char data[N]; ...
for(i=0;i<N;i++) printf("%x",data[i]);
My goal is to represent the data as a String (%s) rather than access it by each element. Since I need the output of the hash as a String for further processing.
Thanks!
So, based on your update, are you talking about trying to convert a unsigned char buffer into a hexadecimal interpretation, something like this:
#define bufferSize 10
int main() {
unsigned char buffer[bufferSize]={1,2,3,4,5,6,7,8,9,10};
char converted[bufferSize*2 + 1];
int i;
for(i=0;i<bufferSize;i++) {
sprintf(&converted[i*2], "%02X", buffer[i]);
/* equivalent using snprintf, notice len field keeps reducing
with each pass, to prevent overruns
snprintf(&converted[i*2], sizeof(converted)-(i*2),"%02X", buffer[i]);
*/
}
printf("%s\n", converted);
return 0;
}
Which outputs:
0102030405060708090A
In C, a string is an array of char, terminated with a character whose value is 0.
Whether or not char is a signed or unsigned type is not specified by the language, you have to be explicit and use unsigned char or signed char if you really care.
It's not clear what you mean by "representing" an unsigned character array as string. It's easy enough to cast away the sign, if you want to do something like:
const unsigned char abc[] = { 65, 66,67, 0 }; // ASCII values for 'A', 'B', 'C'.
printf("The English alphabet starts out with '%s'\n", (const char *) abc);
This will work, to printf() there isn't much difference, it will see a pointer to an array of characters and interpret them as a string.
Of course, if you're on a system that doesn't use ASCII, there might creep in cases where doing this won't work. Again, your question isn't very clear.
Well a string in C is nothing else than a few chars one after another. If they are unsigned or signed is not much of a problem, you can easily cast them.
So to get a string out of a unsigned char array all you have to do is to make sure that the last byte is a terminating byte '\0' and then cast this array to char * (or copy it into a array of char)
I successfully use this to convert unsigned char array to std:string
unsigned char array[128];
std::stringstream buffer;
for (int i = 0; i < 128; i++)
{
buffer << std::hex << std::setfill('0');
buffer << std::setw(2) << static_cast<unsigned>(array[i]);
}
std::string hexString = buffer.str();
An example as you've asked:
unsigned char arr [SIZE];
I have a char array with data from a text file and I need to convert it to hexadecimal format.
Is there such a function for C language.
Thank you in advance!
If I understand the question correctly (no guarantees there), you have a text string representing a number in decimal format ("1234"), and you want to convert it to a string in hexadecimal format ("4d2").
Assuming that's correct, your best bet will be to convert the input string to an integer using either sscanf() or strtol(), then use sprintf() with the %x conversion specifier to write the hex version to another string:
char text[] = "1234";
char result[SIZE]; // where SIZE is big enough to hold any converted value
int val;
val = (int) strtol(text, NULL, 0); // error checking omitted for brevity
sprintf(result, "%x", val);
I am assuming that you want to be able to display the hex values of individual byes in your array, sort of like the output of a dump command. This is a method of displaying one byte from that array.
The leading zero on the format is needed to guarantee consistent width on output.
You can upper or lower case the X, to get upper or lower case representations.
I recommend treating them as unsigned, so there is no confusion about sign bits.
unsigned char c = 0x41;
printf("%02X", c);
You can use atoi and sprintf / snprintf. Here's a simple example.
char* c = "23";
int number = atoi(c);
snprintf( buf, sizeof(buf), "%x", number );