|  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
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:
	parseInt("123", 16).toString(16)		= "123"

	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:

Expected result:

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


Add a Patch

Pull Requests

Pull requests:

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2015-06-26 21:48 UTC]
-Status: Open +Status: Not a bug
 [2015-06-26 21:48 UTC]
Please see the CAUTION note on 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-2022 The PHP Group
All rights reserved.
Last updated: Fri Dec 02 01:05:53 2022 UTC