Skip to content

Instantly share code, notes, and snippets.

@assafshomer
Created June 14, 2015 07:00
Show Gist options
  • Save assafshomer/19380e9acfcb2c3f055c to your computer and use it in GitHub Desktop.
Save assafshomer/19380e9acfcb2c3f055c to your computer and use it in GitHub Desktop.
require 'terminal-table'
def max_num(mantis_bits,available_bits)
mantis(mantis_bits)*(10**exponent(mantis_bits,available_bits))
end
def mantis(mantis_bits)
2**mantis_bits
end
def exponent(mantis_bits,available_bits)
2**(available_bits-mantis_bits)
end
def threshold_mantis?(mantis_bits,available_bits, max_supported_number)
max_num(mantis_bits,available_bits) > 10**(max_supported_number.to_s.length) &&
max_num(mantis_bits+1,available_bits) < 10**(max_supported_number.to_s.length)
end
def calculate_table(max_supported_number, max_bytes)
table = Terminal::Table.new do |t|
t.title = "Encoding for maximum #{max_supported_number.to_s.reverse.gsub(/...(?=.)/,'\&,').reverse} Units"
t << ['Flag (bits)','Significant Digits','Mantis (bits)','Exponent (bits)','Bits','Bytes']
t.add_separator
mantis_bits = 0
(1..max_bytes).each do |total_bytes|
total_bits = 8*total_bytes
byte_flag_bits = (total_bytes == max_bytes ? 2 : 3)
available_bits = total_bits - byte_flag_bits
until threshold_mantis?(mantis_bits,available_bits, max_supported_number) do
break if mantis_bits == available_bits -1
mantis_bits +=1
end
exponent_bits = ([1,max_bytes].include?(total_bytes) ? 0 : available_bits - mantis_bits)
mantis_bits = ([1,max_bytes].include?(total_bytes) ? available_bits : mantis_bits)
significant = total_bytes==1 ? '1-31' : (2**mantis_bits).to_s.size-1
# minus one because e.g. 2^10 is 1024 which is 4 digits but is smaller than 9999 so with 10 bits we cannot support all 4 digit numbers, only all 3 digit numbers
t<<[byte_flag_bits,significant,mantis_bits,exponent_bits, total_bits, total_bytes]
end
end
puts table
end
MAX_BYTES = 7
MAX_UNITS = 10**16
calculate_table(MAX_UNITS, MAX_BYTES)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment