rustbinarybitwise-operatorsexponentiation

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:

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 {}.