santosh said:
Hi,
I needed help in converting a character to the correspoding
hexadecimal values, like the following example,
ASCII value : ABC
Hex Code Value : %41%42%43...
whats the logic of conversion...
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char arr[3] = { 'A', 'B', 'C' };
short cnt;
for(cnt = 0; cnt < 3; cnt++)
printf("%%%x ", arr[cnt]);
fflush(stdout);
return 0;
}
You don't use anything from <stdlib.h>.
That prints the hexadecimal values rather than converting them, but
the original problem statement wasn't very clear so it's probably ok.
(Converting to a string would require some moderately complex memory
management.)
For characters with values less than 16, you print a single digit,
e.g., "%f" rather than "%f". Again, the problem statement wasn't
clear on this point.
You print a spaces between the characters, which is inconsistent with
the example.
Why do you use type short for the array index? It typically saves
only an insigificant amount of data space, and the resulting code
could be larger and slower on many systems. Just use int.
The "%x" format expects an unsigned int; you're giving it a char.
It's likely to work anyway, but it could cause problems -- and proving
that it does what you want is a lot more work than just fixing the
code. This is one of those rare cases where a cast is actually
appropriate.
3 is a magic number (not a huge deal in a snippet like this).
The output isn't terminated by a new-line, so it's not guaranteed to
appear even with the fflush(stdout) (and the standard is unclear on
just what can go wrong).
#include <stdio.h>
int main(void)
{
char arr[3] = { 'A', 'B', 'C' };
const int arr_len = sizeof(arr) / sizeof(arr[0]);
int i;
for (i = 0; i < arr_len; i++) {
printf("%%%02x", (unsigned int)arr
);
}
putchar('\n');
return 0;
}