logo

Programming Languages - Type Casting and Type Conversions

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.

By Language

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

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')

Number to String

Java

To Decimal String

int i;

// append to an empty String
String s = "" + i;

// use String.valueOf
String s = String.valueOf(i);

// use <Number class>.toString();
Integer.toString(i);

Integer i;
String s = i.toString();

To Hex String

Integer.toHexString(20320);
// 4f60

To Binary String

Integer.toBinaryString(8);
// 1000

To Octal String

Integer.toOctalString(8);
// 10

String to Number

Java

// To Float
Float f = Float.valueOf(str);

// To primitive
float f = (Float.valueOf(str)).floatValue();

JavaScript

parseInt(str);
parseFloat(str);

Bytes and Integer

Python: bytes and int

int to bytes

>>> d = bytes([65, 66, 67])
>>> d
b'ABC'

bytes to int

>>> list(b'ABC')
[65, 66, 67]

or

>>> b'ABC'[0]
65
>>> b'ABC'[1]
66
>>> b'ABC'[2]
67

Bytes and Hex

Python: bytes and hex

Use .fromhex() and .hex()

>>> hex(ord('A'))
'0x41'
>>> bytes.fromhex('41')
b'A'
>>> bytes.fromhex('41 42')
b'AB'
>>> bytes.fromhex('41 4243')
b'ABC'
>>> bytes.fromhex('414243')
b'ABC'

another example:

>>> str = "89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00"
>>> str
'89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00'
>>> bytes.fromhex(str)
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00'

bytes to hex

>>> bytes([65, 66, 67])
b'ABC'
>>> bytes([65, 66, 67]).hex()
'414243'

Number to Enum

C++

auto foo_enum = static_cast<Foo>(foo_number);