Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why hexa decode need two digit

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading