Way to know bytes of an int in Python [with bits class thrown in]

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #16
    This is considerably more efficient than the previous version:[code=Python]def ConvDecToBaseVa r3(num, base, dd=False):
    if base > 16 or base < 2:
    raise ValueError, 'The base number must be between 2 and 16.'
    if not dd:
    dd = dict(zip(range( 16), [hex(i).split('x ')[1] for i in range(16)]))
    if num == 0: return ''
    num, rem = divmod(num, base)
    return ConvDecToBaseVa r3(num, base, dd)+dd[rem][/code]This avoids the recursion limit:[code=Python]def ConvDecToBaseVa r4(num, base):
    if num < 2: return str(num)
    if base > 16 or base < 2:
    raise ValueError, 'The base number must be between 2 and 16.'
    dd = dict(zip(range( 16), [hex(i).split('x ')[1] for i in range(16)]))
    ans = ''
    while num != 0:
    num, rem = divmod(num, base)
    ans = str(rem)+ans
    return ans[/code]

    Comment

    Working...