Skip to content

Instantly share code, notes, and snippets.

@todorok1
Last active May 14, 2020 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save todorok1/c8487c90beae26e7d083ed38d6091d4f to your computer and use it in GitHub Desktop.
Save todorok1/c8487c90beae26e7d083ed38d6091d4f to your computer and use it in GitHub Desktop.
using UnityEngine;
using System;
using System.Collections;
/// <Summary>
/// 浮動小数点数をビット列で表示します。
/// </Summary>
public class FloatBit : MonoBehaviour
{
void Start()
{
CompareAddedValueToTarget();
}
/// <Summary>
/// 数値を足す場合と目標となる数値そのものを比較した場合で同じになるか確認するメソッドです。
/// 値はメソッド内で直接指定します。
/// </Summary>
void CompareAddedValueToTarget()
{
// 値を変数にセットします。
float valueA = 0.1f;
// 値を10回足します。
float added = 0;
for (int i = 1; i <= 10; i++)
{
added += valueA;
}
// 目標となる値をセットします。
float targetValue = 1.0f;
// 足した場合とそのままの場合が同じか確認します。
string resultText = "";
if (added == targetValue)
{
resultText = "同じです。";
}
else
{
resultText = "異なっています。";
}
Debug.Log($"足した値 {added} と目標の値 {targetValue} は {resultText}");
// ビット列を表示します。
Debug.Log($"足した値 {(added).ToString("G9")}");
ShowBitArrayText(added);
Debug.Log($"目標の値 {targetValue.ToString("G9")}");
ShowBitArrayText(targetValue);
}
/// <Summary>
/// 引数のfloatの値をビット列に変換してコンソールに出力する処理です。
/// </Summary>
void ShowBitArrayText(float value)
{
// バイト列に変換します。
byte[] byteArray = BitConverter.GetBytes(value);
// ビット列に変換します。
BitArray bits = new BitArray(byteArray);
// 出力する文字列を生成します。
System.Text.StringBuilder sb = new System.Text.StringBuilder();
// リトルエンディアンなので逆順に文字列にします。
for (int i = bits.Count - 1; i >= 0; i--)
{
sb.Append(Convert.ToUInt16(bits[i]));
}
// コンソールに出力します。
Debug.Log($"ビット列 : {sb.ToString()}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment