본문 바로가기
Python

hexa string to Floating-point value

by YJHTPII 2024. 4. 2.
반응형


# hexa string to Floating-point value

# hexa string to Floating-point value

import struct

# Hexadecimal string
hex_string = "43663334"

# Convert hexadecimal string to binary string
binary_string = bin(int(hex_string, 16))[2:].zfill(32)

# Split binary string into sign, exponent, and mantissa
sign_bit = int(binary_string[0])
exponent = int(binary_string[1:9], 2)
mantissa = int(binary_string[9:], 2)

# Calculate the floating-point value
sign = (-1) ** sign_bit
fraction = 1 + (mantissa / 2**23)  # Assuming single precision (23 bits)
value = sign * fraction * 2**(exponent - 127)

print("Floating-point value:", value)
# hexa string to Floating-point value

import struct

def hex_to_float(hex_string):
    # Convert hex string to binary string
    binary_string = bin(int(hex_string, 16))[2:].zfill(32)  # Assuming 32-bit IEEE 754 format

    # Convert binary string to floating point using struct
    return struct.unpack('!f', struct.pack('!I', int(binary_string, 2)))[0]

# Example usage
#hex_code = "40490FDB" #result: 3.1415927410125732
hex_code = "43663334" #result: 230.20001220703125 230.20001220703125

result = hex_to_float(hex_code)
print("Floating point value:", result)
Floating-point value: 230.20001220703125

 

 

 

# Floating-point value to Hexadecimal string

# Floating-point value to Hexadecimal string

import struct

# Floating-point value
float_value = 230.20001220703125

# Convert floating-point value to hexadecimal string
hex_string = hex(struct.unpack('<I', struct.pack('<f', float_value))[0])[2:]

print("Hexadecimal string:", hex_string.upper())
Hexadecimal string: 43663334
반응형

'Python' 카테고리의 다른 글

Pickle In Python  (0) 2024.04.15
[Python] Stock Prediction  (0) 2024.04.15
[python]reactpy  (0) 2024.03.19
mqtt 참고사이트  (0) 2024.03.19
Object Distance & Direction Detection for Blind and Low Vision People  (0) 2024.01.26

댓글