Skip to content

Surprising behavior when right-shifting a negative BigInt #347

@mhogrefe

Description

@mhogrefe

Right-shifting an primitive integer in Rust (and most other languages AFAIK) is equivalent to dividing by a power of 2 and rounding towards -∞. But right-shifting a BigInt rounds towards 0 instead.

You can see the difference by pasting the following into https://play.rust-lang.org/:

extern crate num;

fn main() {
    println!("-1 >> 1 == {} (primitive)", -1 >> 1);
    println!("-1 >> 1 == {} (BigInt)", num::BigInt::from(-1) >> 1);
}

This prints

-1 >> 1 == -1 (primitive)
-1 >> 1 == 0 (BigInt)

If this behavior is intentional it should probably be documented and unit-tested.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions