Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I manipulate binary numbers in Rust?

Tags:

rust

How can I handle and do mathematical operations in Rust, such as adding or dividing two binary numbers?

In Python, there is something like this:

bin(int('101101111', 2) + int('111111', 2))

Which works fine unless you need to use floating point numbers.

like image 749
Hasan A Yousef Avatar asked Jun 14 '26 15:06

Hasan A Yousef


1 Answers

Binary numbers in Rust can be defined using the prefix 0b, similar to the 0o and 0x prefixes for octal and hexadecimal numbers.

To print them, you can use the {:b} formatter.

fn main() {
    let x = 0b101101111;
    let y = 0b111111;
    println!("x + y = {:b} that is {} + {} = {} ", x + y, x, y, x + y);

    let a = 0b1000000001;
    let b = 0b111111111;
    println!("a - b = {:b} that is {} - {} = {} ", a - b, a, b, a - b);

    let c = 0b1000000001;
    let d = 0b111111111;
    println!("c * d = {:b} that is {} * {} = {} ", c * d, c, d, c * d);

    let h = 0b10110101101;
    let r = 0b101;
    println!("h / r = {:b} that is {} / {} = {} ", h / r, h, r, h / r);
    println!("h % r = {:b} that is {} % {} = {} ", h % r, h, r, h % r);
}

The output is:

x + y = 110101110 that is 367 + 63 = 430 
a - b = 10 that is 513 - 511 = 2 
c * d = 111111111111111111 that is 513 * 511 = 262143 
h / r = 100100010 that is 1453 / 5 = 290 
h % r = 11 that is 1453 % 5 = 3 
like image 152
Hasan A Yousef Avatar answered Jun 17 '26 11:06

Hasan A Yousef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!