logo

Polyglot CheatSheet - Type Casting and Type Conversion

Last Updated: 2023-03-02

Type Casting vs Type Conversion

  • type conversion / type coercion: implicit, made automatically by compiler.
  • type casting: explicit, done by the programmer using a cast operator.

C++

Read more: C++ Type Casting

Go

NO implicit conversion in Go: Unlike in C, in Go assignment between items of different type requires an explicit conversion. (Otherwise build would fail.)

var i int = 42
var f float64 = float64(i)
var u uint = uint(f)

i := 42
f := float64(i)
u := uint(f)

Use strconv in the standard library to convert between strings and numbers: https://pkg.go.dev/strconv

Rust

Explicit type conversion (casting) can be performed using the as keyword.

let integer = decimal as u8;

Saturating cast: when casting from float to int. If the floating point value exceeds the upper bound or is less than the lower bound, the returned value will be equal to the bound crossed.

// result is 255
300.0_f32 as u8

// result is 0
-100.0_f32 as u8

// result is 0
f32::NAN as u8

Use unsafe to bypass this, but may overflow:

unsafe {
    // result is 44
    300.0_f32.to_int_unchecked::<u8>()

    // result is 156
    (-100.0_f32).to_int_unchecked::<u8>()
}

Conversions

string to char array

>>> s = "asdf"
>>> [c for c in s]
['a', 's', 'd', 'f']

int to char

>>> chr(97)
'a'

char to int

>>> ord('a')
97

int to binary

>>> format(14, 'b')
'1110'

int to hex

>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
>>> f'{255:#x}', f'{255:x}', f'{255:X}'
('0xff', 'ff', 'FF')