How is type cast executed on hardware?

c, cpu

Solution

It depends on the types involved, obviously. Some casts are just a matter of interpretation, so involve no instructions - eg, `unsigned int` to `int`.

Others may require 'widening' of the data to propagate the sign bit into the high order bits, for example `signed char` to `int`.

The instruction on X86 used for this is `cbw` or `cwde`. http://www.fermimn.gov.it/linux/quarta/x86/cbw.htm

ex: `signed char 0b10000000` must become `int 0b1111111110000000` (for 16-bit int)

Problem

In C, sometimes we cast data type for arithmetic operations, for example: ``` int a = (int)b + (int)c; ``` What does a type cast look like to CPU? What instructions does type cast compile into (x86)? Does type cast harm CPU pipelines?

Original source