Home > DeveloperSection > Forums > How to convert a String to hex and calculate binary result in python
Pravesh Singh

Total Post:411

Points:2881
Posted on    January-27-2015 10:10 PM

 ASP.Net C#  Python-3.4 
Ratings:


 1 Reply(s)
 557  View(s)
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?



Royce Roy
Royce Roy

Total Post:134

Points:938
Posted on    January-27-2015 10:36 PM

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


Don't want to miss updates? Please click the below button!

Follow MindStick