ADVERTISEMENT
ADVERTISEMENT

Rust program to read a number and print bits between given positions

Given an integer number, starting and ending positions, write a Rust program to print the bits between given positions in its binary.
Submitted by Nidhi, on September 25, 2021

Problem Solution:

Here, we will create a 32-bit integer number and then we will print the binary number between two given positions.

Program/Source Code:

The source code to read a number and print bits between given positions is given below. The given program is compiled and executed successfully.

// Rust program to read a number and 
// print bits between given positions

fn main() {
    let mut num:i32 = 428;
    let mut pos1:i32 = 4;
    let mut pos2:i32 = 7;
    let mut cnt:i32 = 0;
    let mut tmp:i32 = 0;
    
    println!("Binary number: {:#02b}",num);
    print!("Binary number between two positions: ");
	
    cnt=pos2;
	
    while cnt >= pos1 
    {
        tmp = num & (1 << cnt);
        if tmp>0
        {
            print!("1");
        }
        else
        {
            print!("0");
        }
        cnt=cnt-1;
    }
}

Output:

Binary number: 0b110101100
Binary number between two positions: 1010

Explanation:

Here, we created three integer variables num, pos1, pos2 that are initialized with 428, 4, 7 respectively. Then we printed the binary number between 4 to 7 positions.

Rust Basic Programs »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.