Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

As (truncating) conversion for BigInt? #404

Open
digama0 opened this issue Mar 2, 2021 · 5 comments
Open

As (truncating) conversion for BigInt? #404

digama0 opened this issue Mar 2, 2021 · 5 comments

Comments

@digama0
Copy link

digama0 commented Mar 2, 2021

I might be missing it, but I don't see a version of Wrapping<u32> or other such wrapping conversions for BigInt. Specifically, I would like to be able to convert n: BigInt to (n % 2^N): uN and (n + 2^(N-1)) % 2^N - 2^(N-1): iN, which is what you would get with as conversion, except that BigInt is not a primitive type so it doesn't have an AsPrimitive implementation. Should this be a new trait, or a function?

@cuviper
Copy link
Member

cuviper commented Mar 10, 2021

I understand the mathematical representation, but what would you actually use this for?

@digama0
Copy link
Author

digama0 commented Mar 11, 2021

Well, my case might not be particularly interesting to you since I'm implementing a programming language which has this as a primitive operation, but it also participates in some commuting diagrams like u64 multiplication being equal to bigint multiplication followed by a truncation (or more generally, any expression involving multiplication, addition, and subtraction on u64 with wrapping semantics is equal to the corresponding expression using entirely bigint types, followed by a truncation operation). It's useful to isolate the truncation part from the other operations.

@digama0
Copy link
Author

digama0 commented Mar 11, 2021

By the way, GMP's mpz_get_ui is prior art, if it helps to justify the existence of such an operation in the library (although that appears to be what I would call n.magnitude().truncate::<u64>(), since it ignores the sign instead of taking the 2's complement as in my proposed implementation).

@cuviper
Copy link
Member

cuviper commented Apr 9, 2021

If you want to write this, I'm open. I think we can add this just in num-bigint for now. A method seems nicer, but I'm not sure what constraints would suffice -- might need a new trait regardless.

@digama0
Copy link
Author

digama0 commented Apr 10, 2021

By a method, do you mean BigInt::truncate_u64, BigInt::truncate_i8, etc. as inherent methods? I can prepare a PR doing that for {BigInt, BigUint}::truncate_{ui}{8, 16, 32, 64, 128} if you want.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants