# Jaacostan

## Data Representation in Rust.

December 10, 2019 Posted by jaacostan
Computer uses a fixed number of bits to represent a piece of data, which could be a number, a character, or symbols. A n-bit storage location can represent up to 2^n different entities.
A single bit can encode either 1 or 0. If we combine two bits, it can encode 4 distinct possibilities (00,01,10,11). For example, a 3-bit memory location can hold one of these eight binary patterns: 000, 001, 010, 011, 100, 101, 110, or 111. Hence, it can represent a maximum of 8 distinct entities. It can be also used to represent numbers 0 to 7. A sequence of 8 bits (2^8) is known as a Byte. A byte can form 2^8=256 distinct entities.

Integers can be represented in 8-bit, 16-bit, 32-bit or 64-bit. while coding a program, you must choose an appropriate bit-length for your integers. Also, an integer can be represented such as unsigned and signed integers.

Unsigned Integers: can represent zero and positive integers.
Signed Integers: can represent zero, positive and negative integers.

An 8-bit unsigned integer has a range of 0 to 255, while an 8-bit signed integer has a range of -128 to 127 - both representing 256 distinct numbers.
This is just an introduction on the data representation. If you are having coding experience, you might already know this concept.
fn main() {
let a:u8 = 128;
println!("a = {}",a);
}

In Rust, while declaring a variable, we usually mention the data representation also. In this way, we instruct the code how much memory the variable will use.
Here in this example, for the variable a, I have mentioned as u8 which means unsigned 8-bit integer.

Mutable vs Immutable.
Immutable: Cannot change the Value
Mutable: Can change the value.

fn main() {
let a:u8 = 128;
println!("a = {}",a);
a = 10;
println!("a = {}",a);
}

This code will return an error as the variable is having two values.

If you want to assign multiple value, then we need to declare the variable using mut command, which explicitly says that the variable is mutable.
fn main() {
let mut a:u8 = 128;
println!("a = {}",a);
a = 10;
println!("a = {}",a);
} 