wention
11/22/2013 - 5:54 PM

converte binary to hex,or hex to binary

converte binary to hex,or hex to binary

/*
 * create by wention 11,23,2013
 */

#define NaN 255
char  decode_table[]  = "0123456789ABCDEF";
//char  decode_table1[] = "0123456789abcdef";
unsigned char encode_table[] = {0,1,2,3,4,5,6,7,8,9,NaN,NaN,NaN,NaN,NaN,NaN,NaN,10,11,12,13,14,15};

void binary_to_hex( unsigned char* binary, //a point of data need to be convert
              unsigned long length,        //size of binary data
              unsigned char* buffer)       //a buffer pointer to receive output note that
      {                                     //  the function does not malloc memory for it
          unsigned long k =0;                   // current buffer writen pointer
          for ( unsigned long i =0; i < length; i++)
          {
              buffer[k++] = decode_table[ binary[i] >> 4];
              buffer[k++] = decode_table[ binary[i] & 0x0F];
          }
      }
////////////////////////////////////////////////////////////////////////////////////
//
//   bool hex_to_binary(unsigned char* hex,    //a point of data need to be convert
//                   unsigned long length,     //size of data
//                   unsigned char* buffer)    //a buffer pointer to receive output note that
//                                                     //  the function does not calloc memory for it




bool hex_to_binary(unsigned char* hex,
                   unsigned long length,
                   unsigned char* buffer)
      {                                  
          unsigned long k=0;
          if ( ( length%2) )
           return false;

          for( unsigned long i =0; i < length/2; i++)
          {
              unsigned char l = encode_table[ hex[ k++]-0x30] << 4;
              unsigned char r = encode_table[ hex[ k++]-0x30];
              buffer[i] = l | r;
          }
          return true;
      }