hex2bin

From: Date: Wed, 03 Jan 2001 04:20:24 +0000
Subject: hex2bin
References: 1 2  Groups: php.dev 
Request: Send a blank email to php-dev+get-42776@lists.php.net to get a copy of this message
Hello, Here's a function hex2bin that does the inverse of bin2hex. Note that it does not throw an error if the input string is not a valid hex string; rather, it will return a garbage string. Perhaps you'll want to change this (or I could do it if there is interest). So: $a = "L"; $a = bin2hex($a); // $a = "4c"; echo hex2bin($a); // prints "L"; I've attached the diff output for the three files from /ext/standard/ that were modified. The main modification was in string.c; those changes are pasted below. Regards, -Matt ----------- ext/standard/string.c ------------- int hexval(unsigned char c) { if(c > 96 && c < 103) return (c - 87); // a - f if(c > 64 && c < 71) return (c - 55); // A - F return (c - 48); // assume its 0-9 } static char *php_hex2bin(const unsigned char *old, const size_t oldlen, size_t *newlen) {
    unsigned char *result = NULL;
    int c;
    size_t i, j;
    result = (char *) emalloc((oldlen / 2) * sizeof(char));
    if(!result) {
        return result;
    }
    for(i = j = 0; i < oldlen; j++) {
        result[j] = (hexval(old[i]) << 4) + hexval(old[i+1]);
        i += 2;
    }
    if(newlen) *newlen = (oldlen / 2) * sizeof(char);
    return result;
} /* {{{ proto string hex2bin(string data) Converts the hex representation of data to bin */ PHP_FUNCTION(hex2bin) {
    zval **data;
    char *result;
    size_t newlen;
    if(ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &data) == FAILURE) {
        WRONG_PARAM_COUNT;
    }
    convert_to_string_ex(data);
    result = php_hex2bin((*data)->value.str.val, (*data)->value.str.len, &newlen);
    if(!result) {
        RETURN_FALSE;
    }
    RETURN_STRINGL(result, newlen, 0);
} /* }}} */

Attachment: [application/octet-stream] hex2bin.diff.tar
« previous php.dev (#42776) next »