0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで10進数をIEEE754形式に変換するプログラムの作成

Posted at

はじめに

こんにちは!今回はPythonを使って、10進数をIEEE754形式に変換するプログラムを作成したので、その内容を紹介します。

IEEE 754とは?

IEEE 754は浮動小数点数を表現するための標準形式です。浮動小数点数は符号部(Sign)、指数部(Exponent)、仮数部(Mantissa)の3つで構成されており、32ビット(単精度)または64ビット(倍精度)形式が主に使用されています。

単精度(32ビット)

・符号部(S):1ビット
・指数部(e):8ビット
・仮数部(f):23ビット

倍精度(64ビット)

・符号部(S):1ビット
・指数部(e):11ビット
・仮数部(f):52ビット

プログラムの概要

以下のPythonプログラムでは、入力された数値をIEEE 754形式に変換する方法を説明します。

・ decimal_to_binary(num, precision)
 10進数を2進数形式に変換します。
・ to_ieee754(num, precision)
 2進数の結果を元にIEEE 754形式のビット列を生成します。

プログラムコード

def decimal_to_binary(num, precision='single'):
    # 整数部分と小数部分を分離
    integer_part = int(abs(num))
    fractional_part = abs(num) - integer_part

    # 整数部分を2進数に変換
    binary_int = ''
    if integer_part == 0:
        binary_int = '0'
    while integer_part > 0:
        binary_int = str(integer_part % 2) + binary_int
        integer_part //= 2

    # 小数部分を2進数に変換(精度に応じて桁数を調整)
    binary_frac = ''
    max_precision = 23 if precision == 'single' else 52
    while fractional_part > 0 and len(binary_frac) < max_precision:
        fractional_part *= 2
        bit = int(fractional_part)
        binary_frac += str(bit)
        fractional_part -= bit

    return binary_int + ('.' + binary_frac if binary_frac else '')

def to_ieee754(num, precision='single'):
    if precision not in ['single', 'double']:
        raise ValueError("精度は'single'か'double'を指定してください")

    # 形式に応じたパラメータを設定
    params = {
        'single': {'bias': 127, 'exp_bits': 8, 'mantissa_bits': 23},
        'double': {'bias': 1023, 'exp_bits': 11, 'mantissa_bits': 52}
    }[precision]

    # 符号ビットの決定
    sign = '1' if num < 0 else '0'

    # 2進数に変換
    binary = decimal_to_binary(abs(num), precision)

    # 正規化して指数を求める
    if '.' not in binary:
        binary += '.'
    point_pos = binary.find('.')
    first_one = binary.find('1')

    if first_one == -1:  # 0の場合
        exponent = 0
        mantissa = '0' * params['mantissa_bits']
    else:
        # 指数の計算
        exponent = point_pos - first_one - 1
        if first_one > point_pos:
            exponent = point_pos - first_one

        # バイアスの追加
        exponent += params['bias']

        # 仮数部の作成
        binary_normalized = binary.replace('.', '')
        mantissa = binary_normalized[first_one+1:]
        mantissa = mantissa + '0' * params['mantissa_bits']  # 必要な長さまで0で埋める
        mantissa = mantissa[:params['mantissa_bits']]

    # 指数部のビット表現
    exponent = bin(exponent)[2:].zfill(params['exp_bits'])

    return {
        'sign': sign,
        'exponent': exponent,
        'mantissa': mantissa,
        'ieee754': sign + exponent + mantissa,
        'format': precision
    }

使用例

以下のコードでプログラムを試すことができます。

number = -83625.7
for format in ['single', 'double']:
    result = to_ieee754(number, format)
    print(f"\n{format.capitalize()}精度形式:")
    print(f"10進数: {number}")
    print(f"符号部S: {result['sign']}")
    print(f"指数部e: {result['exponent']}")
    print(f"仮数部f: {result['mantissa']}")
    print(f"IEEE 754: {result['ieee754']}")

実行結果

Single精度形式:
10進数: -83625.7
符号部S: 1
指数部e: 10000100110
仮数部f: 01000101111010111111010
IEEE 754: 11000010011001000101111010111111010

Double精度形式:
10進数: -83625.7
符号部S: 1
指数部e: 10000110111
仮数部f: 0001000010111101011111101101010000000000000000000000
IEEE 754: 1100001101110001000010111101011111101101010000000000000000000000

まとめ

このプログラムを使うことで、任意の10進数を簡単にIEEE 754形式に変換できます。浮動小数点数の仕組みを理解するための役立つツールになると思います。最後まで読んでくださり、ありがとうございました。もし改善点や質問があれば、ぜひコメントしてください!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?