"Salvatore Di Fazio" <sa***************@gmail.comwrites:
how can I convert a hex string in a sequence of chars?
A string is a sequence of chars.
>
I've thought, if I get a hex string like that:
54657374
I need to get number one for time and convert it in decimal in the
following way:
5x16^7
4x16^6
6x16^5
5x16^4
7x16^3
3x16^2
7x16
4
= number_tot
and now
char buf[256]
sprintf(buf, "%s", number_tot);
is it correct?
I guess not - number_tot seems to be of an integer type not char*.
If you want to convert hex string into a number use strtol(), ie:
#v+
#include <cstdlib>
#include <cstdio>
using namespace std;
int main(int argc, char **argv) {
if (argc==1) {
fptus("need an argument\n", stderr);
return 1;
}
while (--argc) {
char *end;
long num = strtol(*++argv, &end, 16);
if (*end) { /* you could also add errno checking */
fprintf(stderr, "%s: invalid number\n", *argv);
} else {
printf("%d\n", num);
}
}
return 0;
}
#v-
If you want to convert digits "in pairs" do:
#v+
#include <cstdlib>
#include <cstdio>
using namespace std;
int main(int argc, char **argv) {
if (argc==1) {
fptus("need an argument\n", stderr);
return 1;
}
while (--argc) {
char buf[3] = { 0, 0, 0 }, *end;
for (const char *arg = *++argv; arg[0] && arg[1]; arg += 2) {
buf[0] = arg[0];
buf[1] = arg[1];
long num = strtol(buf, &end, 16);
if (*end) {
fprintf(stderr, "%s: invalid number\n", buf);
} else {
printf("%3d ", num);
}
}
putchar('\n');
}
return 0;
}
#v-
--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl>---<jid:mina86*chrome.pl>--ooO--(_)--Ooo--