home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!elroy.jpl.nasa.gov!usc!sol.ctr.columbia.edu!destroyer!ncar!noao!amethyst!organpipe.uug.arizona.edu!news
- From: dave@cs.arizona.edu (Dave Schaumann)
- Newsgroups: comp.lang.c
- Subject: Re: HELP !! Converting non printable characters to HEX
- Message-ID: <1992Sep2.000227.21792@organpipe.uug.arizona.edu>
- Date: 2 Sep 92 00:02:27 GMT
- References: <1992Sep1.152149.1905@cs.uow.edu.au>
- Sender: news@organpipe.uug.arizona.edu
- Reply-To: dave@cs.arizona.edu (Dave Schaumann)
- Organization: University of Arizona
- Lines: 68
- In-Reply-To: u8705957@cs.uow.edu.au (Hitesh Sanghvi)
-
- In article <1992Sep1.152149.1905@cs.uow.edu.au>, u8705957@cs (Hitesh Sanghvi) writes:
- >Hi there;
- > Any suggestion or 'c' code on how to convert non printable
- >characters to hex.
- >My function works for printable ascii characters but does not work
- >on non printable characters.
- >
- >My code is as follows:
- >
- >void
- >dec_to_hex(sin,sout)
- >unsigned char sin[],sout[];
- >{
- > int loop,i;
- >
- > for (loop = 0;loop<4;loop++)
- > {
- > i = (int)sin[loop];
- > sprintf(&(sout[2*loop]),"%02x",i);
- > }
- >}
- >so it takes 4 ch and gives me 8 hex ch onlly when ascii ch is entered.
-
- Well, I don't know why your code doesn't work for you. I tried it out,
- and it seems to work fine for me. However, there are a several things
- I would change about your code:
-
- >dec_to_hex(sin,sout)
- ^^^
- sin is the name of a function defined by the math library. Although you can
- do it, it's poor form to have variables (or functions) with the same name as
- library functions.
-
- >unsigned char sin[],sout[];
- ^^ ^^
- > for (loop = 0;loop<4;loop++)
- ^
- Hard coding magic numbers is a big mistake. Get in the habit of using #define.
-
- Also, IMHO, this function would be much simpler and ultimately more practical
- if it only worked on one character at a time, and if it returned its value.
- you can pass an array for the result if you want, but I find it tends to be
- useful to return values as well (it also costs very little to do so).
-
- With these comments in mind, I would write this code thusly:
-
- unsigned char *char2hex( unsigned char c, unsigned char *buff ) {
-
- sprintf( buf, "%02x", (int)c ) ;
- return buf ;
- }
-
- Really, this is so simple, you might as well make it a macro:
-
- /* note the use of the comma operator so that buf is still "returned" */
- #define CHAR2HEX( c, buf ) ((buf), sprintf( (buf), "%02x", (int)(c) ))
-
- Now, your original loop could be written as
-
- #define N 4
-
- int i ;
-
- for( i = 0 ; i < N ; i++ )
- CHAR2HEX( s_in[i], s_out[i*2] ) ;
-
- --
- Caught an internal error--.brainrc restored
-