EloiStree / HelloCarRcFromScratch

We try to learn how we can use Scratch as an controller for third application like Hello Car RC
0 stars 0 forks source link

Topic: Turn a double as bits 1 11111111111 111...100 #10

Open EloiStree opened 8 months ago

EloiStree commented 8 months ago

Link to parse Double to 1001010 And 10010 to Double https://www.omnicalculator.com/other/floating-point

import struct
import random
import time

def double_to_binary(double_val):
    # Convert double to binary representation
    binary_representation = struct.pack('!d', double_val)
    # Convert binary to text (string of 0s and 1s)
    binary_text = ''.join(f'{byte:08b}' for byte in binary_representation)
    return binary_text

def binary_to_double(binary_text):
    # Convert binary text to binary representation
    binary_representation = bytes(int(binary_text[i:i+8], 2) for i in range(0, len(binary_text), 8))
    # Unpack binary representation to double
    double_val = struct.unpack('!d', binary_representation)[0]
    return double_val

# Example usage:

#while True:
if True:
    original_double = random.uniform(-1e40, 1e40)
    original_double = random.uniform(-1e5, 1e5)
    #original_double =round(original_double, 4)
    binary_text = double_to_binary(original_double)
    converted_double = binary_to_double(binary_text)
    print(f" ")
    print(f" ")
    print(f"Original double: {original_double}")
    print(f"Binary text: {binary_text}")
    print(f"Converted double: {converted_double}")
    time.sleep(5)

Original double: -47809.04 Binary text: 1100000011100111010110000010000101000111101011100001010001111011 Converted double: -47809.04

Original double: 68605.0 Binary text: 0100000011110000101111111101000000000000000000000000000000000000 Converted double: 68605.0

Original double: -45013.4659 Binary text: 1100000011100101111110101010111011101000101001110001110111100111 Converted double: -45013.4659

Original double: -20598.038136171308 Binary text: 1100000011010100000111011000001001110000110100101011001000100100 Converted double: -20598.038136171308