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.
You can do something like
def round256(a):
return int(a / 256) if a % 256 == 0 else (a - a % 256) + 256
a // 256 * 256 instead of int(a / 256)? Even simpler, and works in all cases, is return a + (-a) % 256.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
% operation is unnecessary if you spell this as lambda x: x + (-x) % 256.