はぐれエンジニアつれづれ

デジタルLSI設計(SystemC, SystemVerilog, etc.)の備忘録。はてなダイアリから移行中。

float, doubleの16進数内部表現から値を復元する

16進数内部表現で与えられたfloatやdoubleの変数値を入力として、floatやdoubleに復元するコードを考えた。

入力となる16進数内部表現には、先頭に”0x”または"0X"が付加されていてもよい。

x86_64にて動作確認。処理系依存のコードになっているため、使用時には注意が必要。

#include <iostream>

float hex2float(const std::string& hex)
{
  long hex_l = std::stol(hex, nullptr, 16);
  float *hex_pf = reinterpret_cast<float*>(&hex_l);
  return *hex_pf;
}

double hex2double(const std::string& hex)
{
  long long hex_ll = std::stoll(hex, nullptr, 16);
  double *hex_pd = reinterpret_cast<double*>(&hex_ll);
  return *hex_pd;
}

int main(void)
{
  std::string fstr1 = "40490E56";
  float f1 = hex2float(fstr1);
  std::cout << "float, " << fstr1 << " = " << f1 << std::endl; 

  std::string fstr2 = "0x40490E56";
  float f2 = hex2float(fstr2);
  std::cout << "float, " << fstr2 << " = " << f2 << std::endl; 

  std::string dstr1 = "400921CAC083126F";
  double d1 = hex2double(dstr1);
  std::cout << "double, " << dstr1 << " = " << d1 << std::endl; 

  std::string dstr2 = "0x400921CAC083126F";
  double d2 = hex2double(dstr2);
  std::cout << "double, " << dstr2 << " = " << d2 << std::endl; 

  return 0;
}

実行結果は以下の通り

float, 40490E56 = 3.1415
float, 0x40490E56 = 3.1415
double, 400921CAC083126F = 3.1415
double, 0x400921CAC083126F = 3.1415

ユーザ定義クラスのためのメソッド定義

SystemCでは、ユーザ定義型(クラス)をチャネルのテンプレート引数として使用できる。
ユーザ定義型には、①比較(==)、②標準出力(<<)、③sc_traceの3つの関数が必要とされる。
特に、①はコンパイルエラー回避のため必須である。
②、③は無くてもよいが、デバッグ容易化のために追加が望ましい。

以下では、位置を示す2変数を保持するユーザ定義型pointを例に、①、②を実装した。

まずは、ユーザ定義型のヘッダファイル。
oprerator<<はメンバ関数ではなく、friend関数とする。

#pragma once
#include <iostream>

class point
{
  private:
    int x;
    int y;

  public:
    point(int x, int y); 
    ~point(void);
    bool operator==(const point& obj) const;
    friend std::ostream& operator<<(std::ostream& str, const point& obj);
};

次に、ユーザ定義型の実装ファイル。

#include "userdef.hpp"

point::point(int x, int y)
  : x(x), y(y)
{
};

point::~point(void)
{
};

bool point::operator==(const point& obj) const
{
  return ((this->x == obj.x) && (this->y == obj.y));
};

std::ostream& operator<<(std::ostream& str, const point& obj) 
{
  str << obj.x << "," << obj.y;
  return str;
};

最後に、メイン関数からの呼び出し。

#include <iostream>
#include "userdef.hpp"

int main(void)
{
  point p1( 10, 20 );
  point p2( 11, 20 );
  std::cout << p1 << std::endl;
  std::cout << p2 << std::endl;
  std::cout << (p1 == p2) << std::endl;
  return 0;
};

実行結果は以下の通り。

10,20
11,20
0

次回は、久しぶりにSystemC環境を構築してみる。