# Best way to handle uint > 256 bit

Hi, I was wondering what’s the best way to handle uint greater than 256 bit in solidty. I currently need to calculate 2 simple formulas on-chain, but multiplications can easily overflow the 256 bit limit, 512 bit precision should be sufficient.
Is there any reliable library/package for doing this?

I found the following resources for the moment, but still not sure on what’s the best way of doing it:

Also maybe worth mentioning that end results of the 2 formulas always fits the 256 bit limit.

1 Like

I assume that if the end result doesn’t overflow uint256 then an intermediate step can overflow, hence the need for larger number support.

Unfortunately this is not my area of expertise, so hopefully someone in the community can advise.

1 Like

Exact @abcoathup, intermediate steps can overflow, while the end result always fits the 256 bit limit

1 Like

Hi @bugduino,

James on CryptoDevs suggested having a look at this:

For any library that you were to use, recommend ensuring that it has thorough testing and has been appropriately audited.

1 Like

Thanks for pointing to that response, I was actually looking for something more structured but if nothing comes up I ll see if I can do what I want to achieve without this calculation in some way or I ll try to write my own implementation.

For the moment the solidity-arithmetic lib from gnosis seems the best candidate but I’m still investigating.

1 Like

Hi @bugduino,

I posted the question on Reddit and a couple of chats to see if there were any recommendations.

1 Like

I really appreciate your support @abcoathup, thanks! Let’s see what’s comes up

1 Like

Hi @bugduino,

Response on Reddit from Remco_ the author of https://medium.com/wicketh/mathemagic-full-multiply-27650fec525d

I wrote about the most efficient way to do 256x256 -> 512 multiplication and 512x256 -> 256 division.

Depending on the formula, you might not even need 512 bits. If the final result fits in 256 bit and you stick to ring operations (+, -, *) then overflows will cancel out. If you need to detect overflows, do division or other operations it gets trickier.

`q = a * (s / (s + x)) * (b / (s + x)) * o / k`
it’s clear that posed in this way, `(s / (s + x))` would be < 1 so solidity would truncate that value and return 0, same for `(b / (s + x))` as s > b and b,s,x > 0. So I thought about rearranging the formula to
`q = (a * b * o * s)/(k * (s + x)^2)` but that would have easily overflowed the 256 bit limit.
So I rearranged the initial formula once more to this `q = (a * s / (s + x) * b) / (s + x) * o / k` which seems to be working fine because after every multiplication there is a subsequent division which keeps numbers relatively low.