Opened 7 years ago

Closed 7 years ago

#5812 closed enhancement (fixed)

Faster CPLHexToBinary

Reported by: pramsey Owned by: warmerdam
Priority: normal Milestone: 1.11.2
Component: default Version: 1.11.1
Severity: normal Keywords: hex
Cc:

Description

I found while testing the OGR FDW wrapper (which currently slings piles of data through the pipe) that the hex to binary function is a little less efficient than it could be. For reading through my full table, this version was about 30% faster than the current version. In general for things like PostGIS reading (via hexwkb) this should improve performance.

/************************************************************************/
/*                           CPLHexToBinary()                           */
/************************************************************************/

/**
 * Hexadecimal to binary translation
 *
 * @param pszHex the input hex encoded string.
 * @param pnBytes the returned count of decoded bytes placed here.
 *
 * @return returns binary buffer of data - free with CPLFree().
 */

static unsigned char hex2char[256] = {
    /* not Hex characters */
    20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
    20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
    20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
    /* 0-9 */
    0,1,2,3,4,5,6,7,8,9,20,20,20,20,20,20,
    /* A-F */
    20,10,11,12,13,14,15,20,20,20,20,20,20,20,20,20,
    /* not Hex characters */
    20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
        /* a-f */
    20,10,11,12,13,14,15,20,20,20,20,20,20,20,20,20,
    20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
    /* not Hex characters (upper 128 characters) */
    20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
    20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
    20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
    20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
    20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
    20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
    20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
    20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20
    };


GByte *CPLHexToBinary( const char *pszHex, int *pnBytes )
{
    size_t  nHexLen = strlen(pszHex);
    int i;
    register unsigned char h1, h2;
    GByte *pabyWKB;	

    pabyWKB = (GByte *) CPLMalloc(nHexLen / 2 + 2);
            
    for( i = 0; i < nHexLen/2; i++ )
    {
            h1 = hex2char[(int)pszHex[2*i]];
            h2 = hex2char[(int)pszHex[2*i+1]];

            /* First character is high bits, second is low bits */
            pabyWKB[i] = ((h1 & 0x0F) << 4) | (h2 & 0x0F);
    }
	pabyWKB[nHexLen/2] = 0;
    *pnBytes = nHexLen/2;
	
    return pabyWKB;

}

Change History (1)

comment:1 Changed 7 years ago by Even Rouault

Resolution: fixed
Status: newclosed

Thanks

trunk r28320, branches/1.11 r28321 "CPLHexToBinary(): faster implementation (patch by pramsey, #5812)"

Note: See TracTickets for help on using tickets.