Re: HEXADECIMAL to STRING



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.
.



Relevant Pages

  • Re: socket communication: send & receive doesnt work right
    ... So I don't want to send a string as bytes. ... public void send_doubles(double vals, int len) throws ... // send a short acknowledgement to the server ... char *result; ...
    (microsoft.public.win32.programmer.networks)
  • Re: [PATCH] markers: modpost
    ... pointers to the name/format string pairs. ... The same can then be done with modules using the __markers section. ... +static void read_markers(const char *fname) ... int main ...
    (Linux-Kernel)
  • Re: [PATCH] markers: modpost
    ... This adds some new magic in the MODPOST phase for CONFIG_MARKERS. ... will be a neighbor of its format string. ... +static void read_markers(const char *fname) ... int main ...
    (Linux-Kernel)
  • Re: Is this code totaly a shit?
    ... | void UppStrg(char *Low, char *Upp, int cnt); ... whitespace-delimited string. ... You're also assuming that the representations of the characters ...
    (comp.lang.c)
  • Re: A string collection abstract data type
    ... duplicate string in Insert, InsertAt, ReplaceAt; ... used int instead of size_t for count and size for consistency with API. ... char *(StringCollection *SC, int idx, ... static int IsReadOnly; ...
    (comp.lang.c)