Last active
October 15, 2018 01:07
-
-
Save muyesh/affaa580ba167bf6a8ab1546985cdd93 to your computer and use it in GitHub Desktop.
Amount Compression for Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# Bitcoin Core Amount compression | |
# https://github.com/bitcoin/bitcoin/blob/v0.16.3/src/compressor.cpp#L133 | |
def compress_amount(n) | |
if n == 0 | |
return 0 | |
end | |
e = 0 | |
while (n % 10 == 0) and e < 9 do | |
n /= 10 | |
e += 1 | |
end | |
if e < 9 | |
d = n % 10 | |
n /= 10 | |
return 1 + (n * 9 + d - 1) * 10 + e | |
else | |
return 1 + (n - 1) * 10 + 9 | |
end | |
end | |
def decompress_amount(x) | |
if x == 0 | |
return 0 | |
end | |
x -= 1 | |
e = x % 10 | |
x /= 10 | |
n = 0 | |
if e < 9 | |
d = (x % 9) + 1 | |
x /= 9 | |
n = x * 10 + d | |
else | |
n = x + 1 | |
end | |
while e > 0 do | |
n *= 10 | |
e -= 1 | |
end | |
return n | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment