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
'IT > Python' 카테고리의 다른 글
[Python] 주피터 파일(.ipynb) -> 파이썬 파일(.py) 변환 (0) | 2021.07.08 |
---|---|
[Python] 라즈베리파이(리눅스)에 PyQt, Qt Designer 설치 (0) | 2021.07.06 |
[파이썬] pyCharm에서 pip로 라이브러리 연결하기 (0) | 2021.02.24 |
[Python] matplotlib으로 그래프 그리기 (0) | 2021.02.02 |
[Python] MQTT 통신 (0) | 2021.02.02 |
댓글