hu********@yahoo.com wrote:
Hi All,
I am trying to figure out a right syntax to convert an integer array
into hex array. sprintf worked for me on doing single integer:
Nope, you are converting an array of int into a string containing
a hex representation. You probably want to convert the array of
int into an array of strings which each contain the hex number.
int i, Iarray[8], n=15;
char buf[9];
sprintf(buf, "0x%02x", n);
The above code worked. Howeve, what I am trying to do is to convert an
array. I tried the following syntax, no good:
for (i=0; i<9; i++) sprintf(buff[i], "0x%02x", Iarray[i]);
&buff[i] if any for (i=0; i<9; i++) sprintf(buff + i, "0x%02x", Iarray[i]);
This effectively gives you a buffer overrun as you write
at least four characters plus string terminator to buff[0], buff[1],
...., buff[8], i.e. you occupy buff[0]..buff[12] even though you
only are allowed to access buff[0]..buff[8].
In addition, you access Iarray[8] which also is not available
by you. Even if buf is large enough and Iarray[8] exists, you
effectively could as well write
sprintf(buff, "000000000x%02x", Iarray[8]);
instead of your loops.
Apart from that, %x denotes an argument of type unsigned int,
so we need (unsigned int)Iarray[i].
The right size for buf to contain only n for arbitrary
unsigned int values is
(sizeof(unsigned int)*CHAR_BIT+3)/4
for the hex digits plus 2 for the leading '0' and 'x' plus the
string terminator '\0'. On typical implementations with 32-Bit
unsigned int, this is 11. If you use C99, you should
use snprintf() instead of sprintf() as sprintf() is inherently
unsafe. Then the correct minimum buffer size does not play
as much of a role.
Do not use "magic numbers" explicitly in your code; instead
#define them in one place and only use them.
#define LARGE_ENOUGH 11
#define ARRAY_SIZE 9
size_t i;
int Iarray[ARRAY_SIZE], ret;
char buffers[ARRAY_SIZE][LARGE_ENOUGH];
.....
for (i=0; i<ARRAY_SIZE; i++) {
ret = sprintf(buf[i], "0x%02x", (unsigned) Iarray[i]);
if (ret >= LARGE_ENOUGH) {
/* We already have overwritten the array bounds and are
** deep in undefined behaviour; with a bit of luck, we
** will get this out: */
fprintf(stderr, "LARGE_ENOUGH is not large enough by %d\n",
ret+1-LARGE_ENOUGH);
/* Probably, data was corrupted; die. */
exit(EXIT_FAILURE);
} else if (ret < 0) {
fprintf(stderr, "sprintf failed for i=%lu\n",
(unsigned long) i);
}
}
In C99, we can do the loop somewhat cleaner:
for (i=0; i<ARRAY_SIZE; i++) {
ret = snprintf(buf[i], LARGE_ENOUGH, "0x%02x", (unsigned) Iarray[i]);
if (ret >= LARGE_ENOUGH) {
/* We have not overwritten anything but: */
fprintf(stderr, "LARGE_ENOUGH is not large enough by %d\n",
ret+1-LARGE_ENOUGH);
} else if (ret < 0) {
fprintf(stderr, "sprintf failed for i=%zu\n", i);
}
}
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.