Changing string to byte type in Python 2.7

前端 未结 5 1395
谎友^
谎友^ 2020-12-11 01:42

In python 3.2, i can change the type of an object easily. For example :

x=0
print(type (x))
x=bytes(0)
print(type (x))

it will give me this

5条回答
  •  温柔的废话
    2020-12-11 02:42

    May be not exactly what you need, but when I needed to get the decimal value of the byte d8 (it was a byte giving an offset in a file) i did:

    a = (data[-1:])          # the variable 'data' holds 60 bytes from a PE file, I needed the last byte
                             #so now a == '\xd8'  , a string
    b = str(a.encode('hex')) # which makes b == 'd8' , again a string
    c = '0x' + b             # c == '0xd8' , again a string
    int_value = int(c,16)    # giving me my desired offset in decimal: 216
    
                             #I hope this can help someone stuck in my situation
    

提交回复
热议问题