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.
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.
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.
I have a pointer lpBegin pointing to a string "1234". Now i want this string compare to an uint how can i make this string to unsigned integer without using scanf? I know the string number is 4 characters long.
You will have to use the atoi function. This takes a pointer to a char and returns an int.
const char *str = "1234";
int res = atoi(str); //do something with res
As said by others and something I didn't know, is that atoi is not recommended because it is undefined what happens when a formatting error occurs. So better use strtoul as others have suggested.
Definitely atoi() which is easy to use.
Don't forget to include stdlib.h.
You can use the strtoul() function. strtoul stands for "String to unsigned long":
#include <stdio.h>
#include <stdlib.h>
int main()
{
char lpBegin[] = "1234";
unsigned long val = strtoul(lpBegin, NULL, 10);
printf("The integer is %ul.", val);
return 0;
}
You can find more information here: http://www.cplusplus.com/reference/clibrary/cstdlib/strtoul/
You could use strtoul(lpBegin), but this only works with zero-terminated strings.
If you don't want to use stdlib for whatever reason and you're absolutely sure about the target system(s), you could do the number conversion manually.
This one should work on most systems as long as they are using single byte encoding (e.g. Latin, ISO-8859-1, EBCDIC). To make it work with UTF-16, just replace the 'char' with 'wchar_t' (or whatever you need).
unsigned long sum = (lpbegin[0] - '0') * 1000 +
(lpbegin[1] - '0') * 100 +
(lpbegin[2] - '0') * 10 +
(lpbegin[3] - '0');
or for numbers with unknown length:
char* c = lpBegin;
unsigned long sum = 0;
while (*c >= '0' && *c <= '9') {
sum *= 10;
sum += *c - '0';
++c;
}
I think you look for atoi()
http://www.elook.org/programming/c/atoi.html
strtol is better than atoi with better error handling.
You should use the strtoul function, "string to unsigned long". It is found in stdlib.h and has the following prototype:
unsigned long int strtoul (const char * restrict nptr,
char ** restrict endptr,
int base);
nptr is the character string.
endptr is an optional parameter giving the location of where the function stopped reading valid numbers. If you aren't interested of this, pass NULL in this parameter.
base is the number format you expect the string to be in. In other words, 10 for decimal, 16 for hex, 2 for binary and so on.
Example:
#include <stdlib.h>
#include <stdio.h>
int main()
{
const char str[] = "1234random rubbish";
unsigned int i;
const char* endptr;
i = strtoul(str,
(char**)&endptr,
10);
printf("Integer: %u\n", i);
printf("Function stopped when it found: %s\n", endptr);
getchar();
return 0;
}
Regarding atoi().
atoi() internally just calls strtoul with base 10. atoi() is however not recommended, since the C standard does not define what happens when atoi() encounters a format error: atoi() can then possibly crash. It is therefore better practice to always use strtoul() (and the other similar strto... functions).
If you're really certain the string is 4 digits long, and don't want to use any library function (for whatever reason), you can hardcode it:
const char *lpBegin = "1234";
const unsigned int lpInt = 1000 * (lpBegin[0] - '0') +
100 * (lpBegin[1] - '0') +
10 * (lpBegin[2] - '0') +
1 (lpBegin[3] - '0');
Of course, using e.g. strtoul() is vastly superior so if you have the library available, use it.
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 );
Can anyone suggest means of converting a byte array to ASCII in C? Or converting byte array to hex and then to ASCII?
[04/02][Edited]: To rephrase it, I wish to convert bytes to hex and store the converted hex values in a data structure. How should go about it?
Regards,
darkie
Well, if you interpret an integer as a char in C, you'll get that ASCII character, as long as it's in range.
int i = 97;
char c = i;
printf("The character of %d is %c\n", i, c);
Prints:
The character of 97 is a
Note that no error checking is done - I assume 0 <= i < 128 (ASCII range).
Otherwise, an array of byte values can be directly interpreted as an ASCII string:
char bytes[] = {97, 98, 99, 100, 101, 0};
printf("The string: %s\n", bytes);
Prints:
The string: abcde
Note the last byte: 0, it's required to terminate the string properly. You can use bytes as any other C string, copy from it, append it to other strings, traverse it, print it, etc.
First of all you should take some more care on the formulation of your questions. It is hard to say what you really want to hear. I think you have some binary blob and want it in a human readable form, e.g. to dump it on the screen for debugging. (I know I'm probably misinterpreting you here).
You can use snprintf(buf, sizeof(buf), "%.2x", byte_array[i]) for example to convert a single byte in to the hexadecimal ASCII representation. Here is a function to dump a whole memory region on the screen:
void
hexdump(const void *data, int size)
{
const unsigned char *byte = data;
while (size > 0)
{
size--;
printf("%.2x ", *byte);
byte++;
}
}
Char.s and Int.s are stored in binary in C. And can generally be used in place of each other when working in the ASCII range.
int i = 0x61;
char x = i;
fprintf( stdout, "%c", x );
that should print 'a' to the screen.