Re: HEXADECIMAL to STRING
- From: Ben Bacarisse <ben.usenet@xxxxxxxxx>
- Date: Sun, 03 Jun 2007 16:42:42 +0100
Andrea <acirulli@xxxxxxxxx> writes:
Hi,
suppose that I have a string that is an hexadecimal number, in order
to print this string I have to do:
void print_hex(unsigned char *bs, unsigned int n){
int i;
for (i=0;i<n;i++){
printf("%02x",bs[i]);
}
}
where bs is an hexadecimal string, now i want to create a function
that given bs return a printable string containing the hexadecimal
value of bs, i tried doing this:
int hex2str(char* digest, char* result,int len){
int i;
char *app=malloc(sizeof(char));
result=malloc(strlen(digest));
for (i=0;i<len;i++){
sprintf(app,"%02x",digest[i]);
strcat(result,app);
}
}
You don't need to format each digit and the glue them together, but
you must get all your sizes right first. You have "len" digits. When
tuned into a string, each one needs two characters to represent it and
you need space for a terminating null:
char *result = malloc(<you work it out>);
Note: sizeof char is 1 *by definition* so it is usually left out of
such calculations. You can put the digits in the right place in the
result using pointer arithmetic:
for (i = 0; i < len; i++)
sprintf(<your code here>, "%02x", digest[i]);
Also, you need to understand how to get values out of functions in C.
In your example code, hex2str returns an int, but you don't return
anything. What did you intend? The simplest solution is to return
the string you have just built.
Finally, (at least from me) you *must* test the return from malloc and
deal appropriately with an allocation failure. I have not put this
all together because it looks too much like homework (or coursework as
we tend to call it here in the UK).
--
Ben.
.
- References:
- HEXADECIMAL to STRING
- From: Andrea
- HEXADECIMAL to STRING
- Prev by Date: Re: Converting to/from pointer
- Next by Date: Re: Random String
- Previous by thread: Re: HEXADECIMAL to STRING
- Next by thread: Re: HEXADECIMAL to STRING
- Index(es):
Relevant Pages
|