C++ Tutorial/Development/reinterpret cast

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Use reinterpret_cast to cast from char pointer to integer

#include <iostream>
using namespace std;
int main()
{
  int i;
  char *p = "This is a string";
  i = reinterpret_cast<int> (p); // cast pointer to integer
  cout << i;
  return 0;
}
4448256"

Using reinterpret_cast: cast float to int

#include <cassert>
#include <iomanip>
#include <iostream>
#include <ostream>
using namespace std;
int main()
{
  
  float pi = 1.1;
  int   ipi;
  cout << setfill("0") << showbase << hex << internal;
  assert(sizeof(int) == sizeof(float));
  ipi = reinterpret_cast<int&>(pi);
  cout << "pi bits=" << setw(10) << ipi << "\n";
}
pi bits=0x3f8ccccd