Timeline for How to find numbers in a textfile that are not divisible by 4096, round them up and write new file?
Current License: CC BY-SA 4.0
10 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
Jun 18 at 11:16 | comment | added | ilkkachu |
@PeterCordes, $(( )) is standard and the standard refers to C operators in the context of arithmetic expansion, so ((x-1)|4095)+1 should be fine. (It explicitly doesn't require ++ and -- , and the "standalone" (( .. )) construct isn't standard.)
|
|
Jun 17 at 10:25 | comment | added | Peter Cordes |
((x-1)|4095)+1 uses bitwise OR to safely round up without overflow, and without an expensive division operation or checking remainders. This of course only works for power-of-2 divisors because it relies on binary integer representations. Does /bin/sh support $(( )) math at all? I think that's not part of POSIX sh, so your script should be using /bin/bash or /bin/ksh or anything other than /bin/sh . Bash supports bitwise-OR with | . If you want to check whether rounding-up happened, check for equality of input vs. output.
|
|
Jun 17 at 10:20 | comment | added | Peter Cordes | If I recall correctly, Bash does int64_t math internally, so should be safe for the full range of such integers and thus the full range of file sizes allowed in normal systems. Unless some systems us uint64_t file sizes. | |
Jun 17 at 10:18 | comment | added | Peter Cordes |
This awk works correctly for 2^54 - 4096 (unlike Romeo's answer), but fails for 2^54 - 1 (18014398509481983 ), rounding it up to 2^54 , the nearest representable double-precision float. I wondered whether "num" might stay as a string even after num % 4096 did a rounding conversion and found remainder == 0. But that's not the case with GAWK, presumably what gets printed was round-tripped to double and back and thus was rounded (for exponents >= 53). (en.wikipedia.org/wiki/…).
|
|
Jun 17 at 9:40 | comment | added | ilkkachu |
You could also use if (remainder != 0) num = num + divisor - remainder; printf "%i ", num , since the other branch is a no-op
|
|
Jun 17 at 9:39 | history | edited | ilkkachu | CC BY-SA 4.0 |
let's make the divisor configurable in the AWK script too, and clean it up a bit
|
Jun 17 at 8:41 | comment | added | ilkkachu |
@JeremyBoden, factor feels a bit awkward here, it gives both too much information (the whole breakdown to prime factors, while just divisibility by 4096 is needed), and too little information (it doesn't help in rounding up)
|
|
Jun 17 at 1:19 | history | edited | Hauke Laging | CC BY-SA 4.0 |
added 399 characters in body
|
Jun 17 at 1:13 | comment | added | Jeremy Boden | This might be a possible use case for the factor command:- factor 8192 outputs '8192: 2 2 2 2 2 2 2 2 2 2 2 2 2' | |
Jun 17 at 1:02 | history | answered | Hauke Laging | CC BY-SA 4.0 |