forum

Home / DeveloperSection / Forums / How to convert a String to hex and calculate binary result in python

How to convert a String to hex and calculate binary result in python

Pravesh Singh 2245 27-Jan-2015

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?


Updated on 27-Jan-2015

Can you answer this question?


Answer

1 Answers

Liked By