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

デジタル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