Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's going on with typecasting in C?

Tags:

c

low-level

I get what typecasting in C is doing at a high level. I get that sometimes this is done implicitly, and sometimes is required to be done explicitly. However I don't know how this is happening in low level:

Suppose that GetSignal returns an enum type.

 uint8 outValue;
 f32_t iValue;
 iValue = (f32_t)GetSignal();
 outValue = (uint8)((i32_t)iValue);

My question is what is going on here. I have no idea how the bits are being reorganised after all of these typecasting.

like image 879
Ricardo Mostalac Avatar asked Apr 29 '20 18:04

Ricardo Mostalac


1 Answers

What a cast does is convert a value of one type to a value of another type. What the representation of this value is for each given type depends on the type.

Suppose GetSignal returns an enum with an underlying value of 1. As a 32 bit integer, its representation looks like this (assuming big-endian byte ordering, i.e. high-to-low):

00000000 00000000 00000000 00000001

This integer value of 1 is then converted via an explicit cast to f32_t. Assuming that this type is represented as an IEEE 754 single precision floating point value, its representation (high-to-low) looks like this:

00111111 10000000 00000000 00000000

And this representation is stored in iValue.

Then iValue is cast to i32_t. So the float value 1 with the above IEEE754 floating point representation is converted to the int value 1 with this representation:

00000000 00000000 00000000 00000001

Which is the same as what GetSignal returned. This value is then cast to type uint8 which has this representation:

00000001

And that representation is stored in outValue.

Regarding your comment about adding a float and an int, the usual arithmetic conversion rules dictate that the value with type int is first implicitly converted to type float, then the two float values can be added and the result has type float.

like image 159
dbush Avatar answered Oct 10 '22 17:10

dbush