简体   繁体   中英

C++ double pointer array to float conversion

What is a correct way to convert double to float in c++. Is the conversion implicit?

Question 1: Consider double d = 5.0; and float f;

Which one is correct?

  • f = d;
  • f = (float)d;
  • f = static_cast<float>(d);

Question 2: Now consider we have

char *buffer = readAllBuffer(); 
double *d = (double*)(buffer + offset);
float f;

Which one is now correct?

  • f = d[0];
  • f = (float)d[0];
  • f = static_cast<float>(d[0]);

Thanks in advance!

They all boil down to the same thing, and the use of arrays is a red herring. You can indeed write

float f = d;

Some folk argue that a static_cast makes code more readable as it sticks out so clearly. It can also defeat warnings that some compilers might issue if a less long-winded form is used.

Naturally of course since a double is a superset of float , you might lose precision. Finally, note that for

float f1 = whatever;
double d1 = f1;
float f2 = d1;

, the C++ standard insists that f1 and f2 must be the same value.

You do have one major issue. This is not allowed:

double *d = (double*)(buffer + offset);

It violates strict aliasing and quite possibly alignment requirements. Instead you need to use memcpy :

double d;
memcpy(&d, buffer + offset, sizeof d);
float f = d;

Either of the cast alternative can be substituted for the last line, the important change is from dereferencing an pointer with incorrect type and alignment to making a bytewise copy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM