Conversions

From Coder Merlin
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
Boeing, N780BA, B747-409(LCF) Dreamlifter

Prerequisites[edit]

Introduction[edit]

In some cases we have a value of one type but want to use it in another context, as a different type. Depending on language, this may be referred to as "type conversion", "type casting", or "type coercion". Often, type casting refers to the mere re-interpretation of existing bits, while type conversion creates a new representation of data as a different type.

Type Casting[edit]

When type casting, we consider an existing bit pattern as other than that originally declared. For example, consider the following C program:

#include <stdio.h>
int main(int argc, char *argv[]) {
  int c = 65;
  printf("The value is: %i", c);
  printf("The value is: %c", c);
  return 0;
}

On line 3, we declare an integer variable, "c" and assign the initial value, 65. On line 4, we print the integer value. On line 5, we use the printf command to indicate that we actually have a character, rather than an integer. The existing bit pattern is then re-interpreted and the character "A" is printed. (If you don't remember why it's "A", review W1033 Character Encoding.

Type Conversion[edit]

Type conversion is a more extensive process than type casting because it involves the creation of a new value based on an existing value of a different type.

Key Concepts[edit]

Exercises[edit]

References[edit]