파이썬, float 값 메모리 구조를 int로 해석해서 가져오기
글. 수알치 오상문
이런 float 값이 있다고 하죠.
f = 173.3125
이 값을 그냥 int형으로 변환하는 것이 아니라,
f가 저장된 포맷(실수형) 값을 int 포맷으로 해석해서 가져오고 싶은 경우가 있습니다.
예를 들어, C 언어에서는 아래처럼 가져올 수 있습니다.
float n = 173.3125f;
long i;
i = *(long *) &y; // y 변수 메모리에 접근해서 long 포인터로 캐스팅하여 그 값을 가져온다
그런데 파이썬에서는 데이터 객체 구조상 이런 식의 메모리 접근이 가능하지 않습니다.
그래서 검색을 해보니 아래와 같은 방식이 가능하네요.
아래 예제는 두 가지 방법을 보여줍니다. 두 방법 모두 잘 동작합니다.
# 방법 1
import struct
# float 값 포맷을 int 형태로 해석해서 가져오기
def floatToBits(f):
s = struct.pack('>f', f)
return struct.unpack('>l', s)[0]
# int 값 포맷을 float 형태로 해석해서 가져오기
def bitsToFloat(b): # int 값 포맷을 float 형태로 해석해서 가져오기
s = struct.pack('>l', b)
return struct.unpack('>f', s)[0]
f = 173.3125
int_v = floatToBits(f)
hex_v = hex(int_v)
bits_v = bin(int_v)
print(f) # 원래 값: 173.3125
print(int_v) # int로 해석한 정수 값: 1127043072
print(hex_v) # 16진수 정수 표현: 0x432d5000
print(bits_v) # 비트 표현: 0b1000011001011010101000000000000
print(bitsToFloat(int_v)) # 비트 정수를 원래 float으로: 173.3125
# 방법 2
import ctypes
f = ctypes.c_float(173.3125)
int_v = ctypes.c_int.from_address(ctypes.addressof(f)).value
print(int_v) # 비트 정수: 1127043072
<참조> https://stackoverflow.com/questions/14431170/get-the-bits-of-a-float-in-python
Get the "bits" of a float in Python?
I am looking for the Python equivalent of Java's Float.floatToBits. I found this Python: obtain & manipulate (as integers) bit patterns of floats but does anyone know of a less complicated way?
stackoverflow.com
'Python 활용' 카테고리의 다른 글
파이썬, SimpleHTTPServer / http.server 사용 (0) | 2023.02.09 |
---|---|
파이썬, 유튜브 동영상 다운로드 (0) | 2023.01.23 |
파이썬 GUI 개발 PySimpleGUI 소개 동영상 (0) | 2022.08.09 |
파이썬, httpx (0) | 2022.08.03 |
파이썬, 에러 예외 종류 (0) | 2022.07.24 |