HOW TO CONVERT A STRING TO HEX AND CALCULATE BINARY RESULT IN PYTHON

Pravesh Singh

Total Post:412

Points:2888
Posted by  Pravesh Singh
 926  View(s)
Ratings:
Rate this:

I got stuck with my code, tried anything on this side and many other things Google showed.

To the problem:

I try to convert some code-snips from C# to phyton, but on this special point i got stuck.

public static long decode(string data, int size, int offset = 0)

{

    long value = 0;

 

    for (int i = 0; i < size; ++i) {

        value <<= 6;

        value |= (long)data[offset + i] - 0x30;

    }

 

    return value;

}

The String Data could be something like 1Dh. Based on this I convert each char to the hex-equivalent: 0x31, 0x44, 0x68 and subtract 0x30; so I get 0x1, 0x14, 0x38; In the next step I have to convert to the binary equivalent 000001, 010100, 111000 and merge this to 000001010100111000. From this I want to get the integer meaning, in this case 5432.

Is there a possibility to do this in a smart and easy way in python?

  1. Royce Roy

    Post:149

    Points:1043
    Re: How to convert a String to hex and calculate binary result in python

    It's actually pretty easy, and the translation is pretty straight forward. You can continue to use your bit shifting. The only change is the syntax of for-loop and using ord() to get the integer value from a character.

    def decode(data, size, offset=0):

        value = 0

     

        for ch in data[offset:size]:

            value <<= 6

            value |= ord(ch) - 0x30

     

        return value

    Running this in the interpreter, I get 5432:

    >>> decode("1Dh", 3)

    5432

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!