Application of reinterpret_cast in programming

Source: Internet
Author: User

In some cases, int needs to be converted to uint and double to int64_t to meet the interface type requirements. However, after this conversion, data loss may occur. If you only want to read the original data to adapt to the interface, you can use reinterpret_cast. For example, [cpp] # include <stdio. h> # include <stdint. h> int main () {int64_t I = 0; double d = 1.1; int64_t j = reinterpret_cast <int64_t &> (d ); double j2 = reinterpret_cast <double &> (j); int64_t k = static_cast <int64_t> (d); double k2 = static_cast <double> (k ); printf ("org = % lf, reintterpret forw (double => int64_t) = % ld \ t, reintterpret back (int64_t => double) = % lf \ n", d, j, j2); printf ("org = % lf, static forw (double => Int64_t) = % ld \ t, static back (int64_t => double) = % lf \ n ", d, k, k2);} compiled output result: [SQL] [xiaochu. yh @ tfs035040 cpp] $. /. out org = 1.100000, reintterpret forw (double => int64_t) = 4607632778762754458, reintterpret back (int64_t => double) = 1.100000 org = 1.100000, static forw (double => int64_t) = 1, static back (int64_t => double) = 1.000000. After static_cast is used, the precision data is lost. Reinterpret_cast is a binary conversion that does not care about the data semantics. When using reinterpret, note that the storage space needs to be sufficient. If you convert double to int32_t, the final result will fail.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.