-4

I'm trying to turn a string representing a Hexidecimal number into an int in python without using the int constructor.

For example if I was given

    hexstring = "802"

How would I get that to be

    output = 2050

Without doing

    int("802",16)

How would I go about this?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574

1 Answers1

2
hexstring = "802"
L=len(hexstring)

def val(h_char):
    # Note you need to extend this to make sure the lowercase hex digits are processed properly
    return ord(h_char)- (55 if ord(h_char)>64 else 48)

def sumup(sum,idx):
    global hexstring # global variables are not recommended
    L=len(hexstring)
    return sum + 16**idx*val(hexstring[L-idx-1])

output = reduce(lambda a,b:sumup(a,b),range(L),0))  


Below is just an explanation of the above and doesn't add any value
Processes on a list of [0,1,2] produced by range(L).

For each idx from above list a function call is made as sumup(sum, idx)=sum+16^idx*h_digit_at_idx.(^ is ** is exp in above)

h_digit_at_idx = ord(h_char)- (55 if ord(h_char)>64 else 48)

ord(h_char) produces 48,49...57,65,66,67,68,69,70 for hex characters 0,1...10,A,B,C,D,E,F

ord(h_char)-(55 if ord(h_char)>64 else 48 produces 0,1...10,11,12,13,14,15 for respective chars.

Finally the last argument of the reduce function is 0(which is the initial sum to start with)

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
kaza
  • 2,317
  • 1
  • 16
  • 25
  • Nice, yeah my solution used a "reducer" like 16*a + b (after turning the string into a list of integers in [0,16] with a similar `ord` trick. – jedwards Sep 08 '17 at 20:28
  • Also this will produce unreliable results if lower case letter are input as hex digits. I hope OP can edit the statement to add that extra condition for lowercase hex digits. – kaza Sep 08 '17 at 20:34