Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

For both little endian and big endian?

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

like image 269
SwiftMango Avatar asked Dec 16 '12 19:12

SwiftMango


2 Answers

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.

like image 79
nes1983 Avatar answered Oct 19 '22 23:10

nes1983


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.

like image 34
Jonathan Wood Avatar answered Oct 20 '22 00:10

Jonathan Wood