Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is 2 raised to 4 equal 10?

I was looking into bitwise operators in rust, and I found that

println!("{:X}", 1 << 4);

prints out 10, but 2^4 should equal 16.

Further experimentation, using powers:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let base: i32 = 2;
for i in 1..=5 {
    print!("{:X} ", base.pow(i));
}

will print out
2 4 8 10 20 when it should print out 2 4 8 16 32

Just wondering if you can point me out to anything in the Rust docs that highlights why binary in Rust works like this? And what can I use to do 2^4 = 16?

>Solution :

{:X} print numbers in hexadecimal.
So it prints 10 in base 16 which is 16, the expected answer.

To get the expected result change {:X} to {}.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading