the_martian
the_martian

Reputation: 634

Convert binary to hexadecimal

I'm trying to create a function that takes a binary string and converts it to hex. So far I've only been able to create a function that can convert an int to hexadecimal.

Here is what I have:

def intToHex(num):
    num = abs(num)
    symdict={10:"A",11:"B",12:"C",13:"D",14:"E",15:"F"}
    rlist=[]
    while(num!=0):
        rlist.append(num%16)
        num//=16
    rlist=rlist[::-1]
    for idx, val in enumerate(rlist):
        rlist[idx] = symdict.get(val, str(val))

    print(''.join(rlist))

intToHex(4512)

sample output: 11A0

How can you make a function, without using builtins that converts binary to hexadecimal. Is it possible to modify my function above for that purpose?

Upvotes: 3

Views: 3659

Answers (3)

Kevin Ng
Kevin Ng

Reputation: 2174

This function I wrote is from my library. This library is called the libZ library. This function can convert million of digits of hexadecimal into binary and only limited to how long Python let the strings to be.

If you want to understand how the function worked, I wrote a very detail article on the subject of converting hexadecimal to binary. You can find the article at http://kevinhng86.iblog.website/2017/01/27/working-with-number-converting-binary-and-hexadecimal-python/ .

def binhexZ(invalue):
    wmap = {"0000": "0",
            "0001": "1",
            "0010": "2",
            "0011": "3",
            "0100": "4",
            "0101": "5",
            "0110": "6",
            "0111": "7",
            "1000": "8",
            "1001": "9",
            "1010": "A",
            "1011": "B",
            "1100": "C",
            "1101": "D",
            "1110": "E",
            "1111": "F"
            }
    i = 0
    output = ""

    while (len(invalue) % 4 != 0):
        invalue = "0" + invalue

    while (i < len(invalue)):
        output = output + wmap[invalue[i:i + 4]]
        i = i + 4

    output = output.lstrip("0")
    output = "0" if len(output) == 0 else output

    return output

Upvotes: 2

Stephen Rauch
Stephen Rauch

Reputation: 49812

Since you already have int to hex, here are some binary string routines:

Code:

def bin_to_int(bin):
    return sum([(1 << i) for i, c in enumerate(reversed(bin)) if c == '1'])

def int_to_bin(num):
    bin = ''
    while num:
        bin = '01'[num & 1] + bin
        num = num >> 1
    return bin

Test code:

print(bin_to_int('1001'))
print(int_to_bin(bin_to_int('1001')))

Produces:

9
1001

Upvotes: 2

devDeejay
devDeejay

Reputation: 6059

You can add some code to your existing function that first converts Binary to Int and then Int to HexaDecimal (your code) OR develop some logic to convert Binary to HexaDecimal directly.

Upvotes: 2

Related Questions