Rust for Python Developers - Unsigned, Signed Integers and Casting

Shin_O
33.7K 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 a Signed Type

Method 1

This is the same as above but you need to be aware that the min/max number of the data type.

i8's min and max numbers are -128 and 127. So the number needs to be between them.

Casting 128 to i8 :

128-256=-128

Casting 1000 to i8:

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

Method 2

1000₁₀ in decimal is 11 1110 1000₂ in binary. The MSB within 8-bit is 1, so it is a negative number. Then use 2’s complement. The complement is 00010111₂ and we add 1₂ becomes 00011000₂. Finally, it is -24₁₀.

4-bit word-4

When the MSB within 8-bit is 0, it is a positive number. Then take the first 8 least significant bits (LSB).

4-bit word-5

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