Re: [問題] reinterpret_cast的問題
: 請教各位
:
: int n=9;
: double d=reinterpret_cast<double &>( n);
: cout<<d;
:
: 為什麼要在 cast那邊加上一個&???代表的是什麼意思....
:
: 如果我沒有加上&
:
: 出現錯誤
:
: 'reinterpret_cast' : 無法由 'int' 轉換為 'double'
:
: 好奇怪 轉成reference 的解釋也不對......
→
04/01 00:20,
04/01 00:20
→
04/01 00:20,
04/01 00:20
→
04/01 00:20,
04/01 00:20
reinterpret_cast 是用在 integral value 與 address value 之間的變換
或是不同 type 的 address value 變換(編譯器對此值的觀點)。
當你把一個 address value(T*, T 為任意 type) reinterpret 成 double* value,
對於接下來 dereference 此 pointer value 的 expression,compiler 產生的
instructions 就是從此 address 處取 sizeof(double) bytes 來解讀成 double
value(依照 IEEE 754 Floating-Point 格式)。
至於你提到把一個 int variable(value=9) reinterpret 成 float* 再 dereference
得到的 float value 約為 1.267xxxx * 10^-44。
依照單精度浮點數的格式來計算:
Sign
Exponent
Fraction
9(int value) bit pattern:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1
= 9 * 2^-23 * 2^-126
= 9 * 2^-149
~= 1.2611686178923354 * 10^-44
細節可以參考類似的網頁:
http://steve.hollasch.net/cgindex/coding/ieeefloat.html
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.173.134.87
※ 編輯: sbrhsieh 來自: 218.173.134.87 (04/01 01:21)
※ 編輯: sbrhsieh 來自: 218.173.134.87 (04/01 01:21)
※ 編輯: sbrhsieh 來自: 218.173.134.87 (04/01 01:27)
推
04/01 01:37, , 1F
04/01 01:37, 1F
→
04/01 01:44, , 2F
04/01 01:44, 2F
推
04/01 09:55, , 3F
04/01 09:55, 3F
討論串 (同標題文章)
完整討論串 (本文為第 3 之 3 篇):