hi, 
 
i have a script that converts hex to bin and bin to hex back. however, when 
converting back to hex the leading 0s are truncated. how to maintain the 
leading 0s? tq
 
import binascii
import string
def byte_to_binary(n): 
    return ''.join(str((n & (1 << i)) and 1) for i in reversed(range(8))) 
 
def hex_to_binary(h): 
    return ''.join(byte_to_binary(ord(b)) for b in binascii.unhexlify(h)) 
def bintohex(s):
    return ''.join([ "%x"%string.atoi(bin,2) for bin in s.split() ])

array0 = '000a00000003c0000030000c1f800000'
a=hex_to_binary(array0)
print "Convert array0 to bin:",a
print "Convert array0 back to hex:",bintohex(a)
if bintohex(a)==array0:
    print "Match"
else:
    print "Not match"

#########result######################
>>> 
Convert array0 to bin: 
00000000000010100000000000000000000000000000001111000000000000000000000000110000000000000000110000011111100000000000000000000000
Convert array0 back to hex: a00000003c0000030000c1f800000
Not match
>>>                                       
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to