More about Integers
Odin supports the following signed integers i8, i16, i32, i64 and i128. These numbers can hold negative numbers.
One bit is used to represent sign (negative or positive) and the rest hold the magnitude. For example, i8 is an 8-bit integer. 1 bit contains the sign. The remaining 7 bits can hold numbers from 0 to . So the range of i8 is -127 to 127.
int is a platform specific type. On most modern systems (which are 64 bit), it is i64. On older systems it is i32.
flowchart LR; subgraph "Signed Integer" s["Sign (1 bit)"] m["Magnitude (k - 1 bits)"] end
Unsigned integers
Odin has integers which can represent only positive numbers: u8, u16, u32, u64, and u128 and the platform specific uint. E.g. u8 can hold values from 0 to .
What to use?
In most cases, you can just use int or uint. Even on a 32-bit system, int can hold numbers up to a few billions which is often sufficient.
For specific use cases like age, you can use u8 because it lies in between 0-256. Smaller integers take less space and can be more efficient.
Integer Overflow
Consider this snippet. We set a to 255 which is the maximum value an u8 can represent. What happens if we add 1 to it?
a:u8 = 255
b := a + 1
fmt.println(b)
In Odin the integer types wrap around. You go back to 0. Similar thing happens when you try to subtract 1 from 0. The number will underflow to 255.
We should use sufficiently large integer types and pay attention to the possibility in our code.
Exercise
Use a calculator to determine the range of integers for u128 and i128. Can you think of a use case for these integer types?