Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert binary to hexadecimal

Tags:

python

hex

binary

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?

like image 976
the_martian Avatar asked May 04 '26 16:05

the_martian


1 Answers

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
like image 50
Stephen Rauch Avatar answered May 07 '26 05:05

Stephen Rauch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!