php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #69947 hex2bin: allow odd-length string
Submitted: 2015-06-26 21:24 UTC Modified: 2015-06-26 21:48 UTC
From: marc at mabe dot berlin Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 7.0Git-2015-06-26 (Git) OS:
Private report: No CVE-ID: None
 [2015-06-26 21:24 UTC] marc at mabe dot berlin
Description:
------------
The current behavior on converting a hexadecimal string with an odd-length into binary data results into a warning and returns false.

As the input is in hexadecimal notation it should be very valid to remove "0" from the left.

This behavior is really annoying as it's not enough the check for valid characters it's required to check the length, too.

Additionally within PHP itself the behavior is inconsistent:
	bin2hex(hex2bin("123"))				= Warning: hex2bin(): Hexadecimal input string must have an even length
	dechex(0x123)					= "123"
	base_convert(base_convert("123", 16, 2), 2, 16)	= "123"
	bin2hex(pack('H*', '123'))			= "1230" (pack() will be part of another bug report)

And on looking into JS and (My)SQL it's working well and can result in an odd-length:
JavaScript:
	parseInt("123", 16).toString(16)		= "123"

MySQL:
	SELECT HEX(UNHEX('123'))			= "0123"
	SELECT HEX(0x123)				= "0123"

I have also found #61660 & #65155 where bin2hex(hex2bin("123")) was resulting into "12" or false without any notice which was surly wrong but simply adding a warning and returning false isn't a good fix in my opinion.

Test script:
---------------
bin2hex(hex2bin("123"))

Expected result:
----------------
"0123"

Actual result:
--------------
Warning: hex2bin(): Hexadecimal input string must have an even length

Patches

Pull Requests

Pull requests:

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-06-26 21:48 UTC] nikic@php.net
-Status: Open +Status: Not a bug
 [2015-06-26 21:48 UTC] nikic@php.net
Please see the CAUTION note on http://php.net/hex2bin. hex2bin does NOT convert a hexadecimal number to a binary number. It decodes a hexadecimally encoded binary strings. Stripping a leading 0 would corrupt the whole string.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Dec 21 13:01:31 2024 UTC