LoginSignup
12

More than 5 years have passed since last update.

ビット表現を完全に保ったキャスト (C++)

Posted at

背景

float や double のビット表現に触れたい時って多いですよね?

しかし,それらの型ではビット演算は行えません.ポインタは reinterpret_cast で変換できるのですが,値そのものは変換できません.かといって一旦ポインタを経由するのも格好悪いです.

作ったもの

そこで,C++11 で覚醒した union を使って,以下のようなキャストもどきを作りました.

template<typename T, typename U>
union raw_cast {
 public:
  constexpr raw_cast(T t) : t_(t) {}
  operator U() const { return u_; }

 private:
  T t_;
  U u_;
};

利用例

Ideone に全体を置きました. https://ideone.com/RWLtqI

コード

  float a = 1.0f;
  uint32_t b = raw_cast<float, uint32_t>(a);
  cout << bitset<32>(b) << endl;

出力

00111111100000000000000000000000

実例

昨日公開した高速単調順位キューライブラリ radix-heap で使ってます. https://github.com/iwiwi/radix-heap

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
12