The hex Python function produce 0x0 for the 0 number:
>>> hex(0)
'0x0'
But bytes.fromhexa only accept hexa with minimum of two digits:
>>> bytes.fromhex(hex(0)[2:])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: non-hexadecimal number found in fromhex() arg at position 1
>>> bytes.fromhex('00')
b'\x00'
Why bytes.fromhexa accept hexa from two digits and no with one digit ?
>Solution :
The fromhex() method is defined in the bytes class. You can find this in Objects/bytesobject.c. Here
PyObject *bytes_fromhex(PyObject *self, PyObject *arg) {
// Convert argument to a string
if (!PyArg_Parse(arg, "s", &hex_str)) {
return NULL;
}
// Check if length of hex_str is even
if (strlen(hex_str) % 2 != 0) {
PyErr_SetString(PyExc_ValueError, "non-hexadecimal number found in fromhex() arg");
return NULL;
}
// Conversion logic...
}
As you can see , the function first checks the length of the input string (hex_str). If the length of hex_str is not even (% 2 != 0), it raises a ValueError with a message indicating that there’s a non-hexadecimal number.
After the length check, the function proceeds to convert the hexadecimal string into bytes.
for (size_t i = 0; i < strlen(hex_str); i += 2) {
// Process pairs of hex characters...
}
so from this logic
If you provided a single digit (like 0), it wouldn’t know how to interpret it. It could be thought of as incomplete since there isn’t a second digit to complete the byte representation.
if bytes.fromhex('0') were allowed, Python would have to guess how to pad it (as 00 or 0F), which introduces ambiguity.