Rust for Python Developers - Unsigned, Signed Integers and Casting

Shin_O
33.6K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

This story was originally published on Medium

Follow me:

Casting to an Unsigned Type

Method 1

When you cast to an unsigned type, T, T::MAX + 1 is added or subtracted until the value fits into the new type.

Example 1: Casting 1000 from the default, i32 to u8

u8 has the max number of 255, so we subtract 255+1, which is 256 from 1000 until it gets less than 255.

1000 - 256             = 744 
1000 - 256 - 256       = 488 
1000 - 256 - 256 - 256 = 232

Method 2

1000₁₀ in decimal is 11 1110 1000₂ in binary. We can take the last 8 bits, which is 1110 1000 and it is 232 in decimal.

An interesting number is 256₁₀.

25610 is 1000000002 in binary. If you take the last 8 bits it is 00000000.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content