RSS Forums RSS
Please support our C++ advertiser: Programming Forums

unsigned character pointer to Hex values

Join Date: Apr 2004
Posts: 3,809
Reputation: Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light Dave Sinkula is a glorious beacon of light 
Rep Power: 17
Solved Threads: 147
Colleague
Dave Sinkula's Avatar
Dave Sinkula Dave Sinkula is offline Offline
long time no c

Re: unsigned character pointer to Hex values

  #4  
Aug 19th, 2005
Perhaps discard the standard routines and roll your own.
#include <stdio.h>
#include <ctype.h>

unsigned char *foo(unsigned char *dst, const unsigned char *src)
{
   static const unsigned char nibble[] = 
   {
      '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
   };
   unsigned char *start = dst;
   while ( *src )
   {
      *dst++ = nibble [ *src >> 4    ];
      *dst++ = nibble [ *src++ & 0xF ];
   }
   *dst = '\0';
   return start;
}

unsigned char *bar(unsigned char *dst, const unsigned char *src)
{
   unsigned char *start = dst;
   while ( *src )
   {
      if ( isdigit(*src) )
      {
         *dst = *src++ - '0';
      }
      else
      {
         *dst = *src++ - 'A' + 10;
      }
      *dst <<= 4;
      if ( isdigit(*src) )
      {
         *dst++ += *src++ - '0';
      }
      else
      {
         *dst++ += *src++ - 'A' + 10;
      }
   }
   *dst = '\0';
   return start;
}

int main(void)
{
   const unsigned char abc[] = "ABCMNO";
   unsigned char over [ sizeof abc * 2  - 1 ], back [ sizeof abc ];
   printf("\"%s\" -> \"%s\"\n", abc,  foo(over, abc));
   printf("\"%s\" -> \"%s\"\n", over, bar(back, over));
   return 0;
}

/* my output
"ABCMNO" -> "4142434D4E4F"
"4142434D4E4F" -> "ABCMNO"
*/
This is for ASCII, and I think it is right. But I was wrong with it a minute ago.
Last edited by Dave Sinkula : Aug 20th, 2005 at 12:23 am. Reason: Got rid of temporary variables.
High Plains Blogger #plains #lounge ## I, for one, welcome our new socialist overlords.
"Capitalism is the unequal distribution of wealth. Socialism is the equal distribution of poverty."
Reply With Quote  
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 6:57 pm.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC