Is there any char to hexadecimal function for C? - c

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 );

Related

Convert a decimal higher than 9 int to char in C

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.

Leading zeros in Hexadecimal int variable C

I converting binary to HEXA but i need output with leading zeros. I use this number in this function -> creat(outfile, hexa_num); From 011101110111 I will get 777 but i need 0777. Here is my converting function. Any suggestions ?
char bin_final[]="011101110111";
char *a = bin_final;
int hexa_num = 0;
do {
int b = *a=='1'?1:0;
hexa_num = (hexa_num<<1)|b;
a++;
} while (*a);
Easy, just use strtoul() and regular snprintf(), no need to re-invent anything.
const unsigned long number = strtoul("011101110111", NULL, 2);
char buf[16];
snprintf(buf, sizeof buf, "%04lx", number);
puts(buf);
This prints
0777
Of course if you want to always just print it you can collapse the final three lines into just:
printf("%04lx\n", number);
You can use %04d: the 0 means leading Zeros in 4 digits.
e.g.:
printf("%04d", hexanum);
If you want it in an string use sprintf instead of printf. The number (int hexa_num) itself doesn't have leading zeros but you can format it, just as you have your binary number not as a number but as a character string.

C Programming: Convert Hex Int to Char*

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.

Getting a hex value from a "0x4000" (for example) string and storing it in a variable.

Here's my issue:
I have written a function to detect if a string is hex based off of the "0x####" format:
int lc3_hashex(char *str)
{
int val = 0;
char *to;
to = strndup(str+2, 10);
val = sscanf(to, "%x", &val);
if (val)
{
return val;
}
return 0;
}
Assuming the parameter is of the form "0x####", it returns the decimal version of the post "0x" numbers. But is there any built in way (or a way I am just overseeing) to get the integer value of the hexidecimal number "0x4000" as opposed to the integer value of "4000"?
Thanks.
You can reduce that function to:
int cnt = sscanf(str, "%x", &val);
if (cnt == 1) {
// read a valid `0xNNNN` string
}
scanf with the %x format already does the hex conversion, and deals with the 0x prefix just fine. Also, it's return value is the number of items matched, so you can use that to determine if it did find a hex value in str or not.
With this you have both pieces of information you need: whether or not the string was formatted as you expected it, and what value it was (properly converted). It also avoids a string allocation (which you're not freeing), and the bug your code has if strlen(str) is less than two.
If you change your function signature to:
int check_and_get_hex(const char *str, int *val);
(or something like that), update the sscanf call accordingly (passing val rather than &val), and return (cnt == 1), you can get both the "it's a valid hex string" and the value to the caller in a single shot.
Use strtol from stdlib.h and specify the base as 16.
The only downside is that this function returns 0 upon failure, so you'll want to check to make sure the input to it is not 0.
I fail to understand why the string is being cut short before doing sscanf. If you want the string in hex value to be converted to the decimal integer, you can give it directly.
#include<stdio.h>
int main()
{
char sHex[7] = "0x2002";
int nVal = 0;
sscanf( sHex, "%x", &nVal );
printf( "%d", nVal );
return 0;
}
This will print 8194, the decimal value for 0x2002. By giving "%x" to sscanf, you are specifying the input string as hexadecimal. so, the preceding "0x" is fine.

How to cast from hexadecimal to string in C?

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 ;)

Resources