This story was originally published on Medium
Follow me:
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
i32
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
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.
1110 1000
An interesting number is 256₁₀.
25610 is 1000000002 in binary. If you take the last 8 bits it is 00000000.
00000000
The #1 tech hiring platform