Skip to content

Instantly share code, notes, and snippets.

@muyesh
Last active October 15, 2018 01:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muyesh/affaa580ba167bf6a8ab1546985cdd93 to your computer and use it in GitHub Desktop.
Save muyesh/affaa580ba167bf6a8ab1546985cdd93 to your computer and use it in GitHub Desktop.
Amount Compression for Ruby
#!/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