0

How can I set a custom round function in Python? I want to round an integer with a step of 256, by only increasing it.

Example : 400 turns into 512, 1026 turns into 1280...

Any suggestions about how I could proceed?

Thanks.

3 Answers 3

2

You can do something like

def round256(a):
    return int(a / 256) if a % 256 == 0  else (a - a % 256) + 256
Sign up to request clarification or add additional context in comments.

2 Comments

Oh you're right, I should have thought about using modulo! Thank you.
I guess you want a // 256 * 256 instead of int(a / 256)? Even simpler, and works in all cases, is return a + (-a) % 256.
2

Sounds like you want the math.ceil function scaled to an arbitrary number:

>>> from math import ceil
>>> def round_step(n, step):
...     return ceil(n / step) * step
...
>>> round_step(400, 256)
512
>>> round_step(1026, 256)
1280

Comments

1

My solution would be:

roundTo256 = lambda x: x + (256 - x%256)%256

First it calculates the distance to the next multiple of 256 (256 - (x % 256)), then it does %256 on that. This is because it would be wrong for a multiple of 256, e.g. 1024 -> 256, so the value is anywhere from 1 to 256. From 1 to 255, %256 has no effect, but 256 % 256 = 0, so it results in 0. Then it just adds the result to the original number

1 Comment

The extra % operation is unnecessary if you spell this as lambda x: x + (-x) % 256.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.