Search code examples
cpointersbytereinterpret-cast

c programming question on reinterpret_cast


What is the reinterpret_cast of (char) doing here?

 unsigned int aNumber = 258; // 4 bytes in allocated memory [02][01][00][00]
 printf("\n is printing out the first byte %02i",(char)aNumber); // Outputs the first byte[02]

Why am i getting out the first byte without pointing to it? such as (char*)&aNumber

is the %02i doing this = (char)*&aNumber

or is the reinterpret_cast of (char) cutting out the rest 3 bytes since it is a char it only allocate one byte of them 4 bytes?


Solution

  • First, reinterpret_cast is a C++ operator. What you've shown is not that but a C-style cast.

    The cast is converting a value of type unsigned int to a value of type char. Conversion of an out-of-range value is implementation defined, but in most implementations you're likely to come across, this is implemented as reinterpreting the lower order bytes as the converted value.

    In this particular case, the low order byte of aNumber has the value 0x02, so that's what the result is when casted to a char.