본문 바로가기
  • "하나씩 기록하다보면 누군가에게 도움이 되지 않을까"
IT/Python

[Python] Hex <-> Float, Double, Ascii, Decimal 변환

by raVineL 2021. 5. 12.
728x90

python 3.7 기준

- 소스

import struct
import numpy as np
import binascii

#float
#0x42161168
#37.517

# double
#0x4042c22d0e560419
#37.517
hex_encoded = "42161168"
hex_encoded2 = "4042c22d0e560419"
def float16_to_hex(f):
    return hex(struct.unpack('<H', np.float16('117.0').tobytes())[0])
def float_to_hex(f):
    return hex(struct.unpack('<I', struct.pack('<f', f))[0])
def double_to_hex(f):
    return hex(struct.unpack('<Q', struct.pack('<d', f))[0])

def hex_to_float(f):
    return struct.unpack('!f', bytes.fromhex(f))[0]
def hex_to_double(f):
    return struct.unpack('!d', bytes.fromhex(f))[0]
    #return struct.unpack('d', f.decode("hex"))

def hex_to_ascii(f):
    return binascii.unhexlify(bytes(f,'utf-8'))
def ascii_to_hex(f):
    return binascii.hexlify(bytes(f,'utf-8'))

def int_to_hex(f):
    return hex(f)
def hex_to_int(f):
    return int(f , 16)

print("abcd")
# ascii to hex
print(ascii_to_hex("abcd"))
# hex to ascii (type byte)
print(hex_to_ascii("61626364"))
# hex to ascii (type str)
print(str(hex_to_ascii("61626364"),'ascii'))
print(" ")

# float16 to hex (type hex)
print(float16_to_hex(37.517))
# float to hex (type hex)
print((float_to_hex(37.517)))
# float to hex (type str)
print(float_to_hex(37.517).replace("0x",""))
# double to hex (type hex)
print(double_to_hex(37.517))
print("  ")

# hex to float
print(hex_to_float(hex_encoded))
# hex to double
print(hex_to_double(hex_encoded2))
# hex to float
print(hex_to_float(float_to_hex(37.517).replace("0x","")))

#decimal to hex
print(int_to_hex(100))
#hex to decimal
print(hex_to_int(int_to_hex(100)))

- 결과

abcd
b'61626364'
b'abcd'
abcd
 
0x5750
0x42161168
42161168
0x4042c22d0e560419
  
37.516998291015625
37.517
37.516998291015625
0x64
100
728x90

댓글