SwiftMango
SwiftMango

Reputation: 15294

Is it always safe to cast char to int and int to double?

For both little endian and big endian?

What if they are in an array? Is it safe too?

Upvotes: 5

Views: 786

Answers (2)

nes1983
nes1983

Reputation: 15756

This has nothing to do with Endianness.

As you can see here, char is almost certainly going to be 8 bit, so casting that to integer is always safe in every sense of the word.

Casting an int to a double, however, is not. The number 2^63 - 10, e.g., cannot be represented exactly in a 64 bit double. Read What Every Computer Scientist Should Know About Floating-Point Arithmetic. Here, a cast will lead to the number being truncated, and thus precision loss.

Fortunately, all 32 bit ints can be casted without loss, so if your ints 32 bits long, you're good.

Upvotes: 3

Jonathan Wood
Jonathan Wood

Reputation: 67223

Yes, as long as you are type casting regular C variables, it is safe.

You only need to worry about endian if you are altering or moving with the raw bytes that make up those variables.

Upvotes: 2

Related Questions