library(lofi)

Conversion to/from low-fidelity representation

Underneath pack() an unpack() is a suite of low-level functions for handling each particular supported type

64-bit (double precision) floating point to Lofi

Double precision floating point values are converted to low-fidelity representation by truncating the mantissa, and re-encoding the exponent. Low-fidelity floats have limited range, poorer precision, and will almost never give back the exact starting value when unpack()ed.

The following converts a double into a 10 bit float (with a sign bit, 2-bit exponent and 7-bit mantissa). The reconstructed double is close to the original value, but not an exact match.

Representation Bits Value Bit layout
Double precision 64 -1.234
Lofi double dbl_to_lofi(-1.234, float_bits = c(1, 2, 7)) 10 669L
Reconstructed double lofi_to_dbl(669L, float_bits = c(1, 2, 7)) 64 -1.226562

RGB Hex Colour to Lofi

  • Hex colours are converted to lofi representation by considering each of the three 8-bit colour channels and quantizing the value into fewer bits.
  • The number of bits can be specified individually for the separate R, G and B colours.
  • The folowing shows that the reconstructed colour isn’t identical to the original, but it is still a reasonable approximation.
Representation Bits Value Colour sample or bit layout
Original colour 24 #123456
Low-fidelity colour hex_colour_to_lofi('#123456', rgb_bits = c(3, 3, 2))) 8 5L
Reconstructed colour lofi_to_hex_colour(5L, rgb_bits = c(3, 3, 2)) 24 #002455

Integer to Lofi

  • Integers are converted to low-fidelity representation by truncacting any leading zeros (or, in the case of negative numbers, truncating the leading ones)
  • Keeping a leading bit for the sign is optional, and if it is excluded then the lofi representation is only able to hold positive numbers
  • lofi correctly keeps the sign bit and twos-complement for negative values
Representation Bits Value bit layout
Original integer 32 -12
Low-fidelity integer int32_to_lofi(-12L, nbits = 5, signed = TRUE) 5 20L
Reconstructed integer lofi_to_int32(20, nbits = 5, signed = TRUE) 32 -12

Choice to Lofi

  • Convert a value into a zero-based index into a list of options.
  • This is similar in idea to how a factor works in R
options <- c('apple', 'banana', 'carrot', 'dog')
choice  <- c('apple', 'apple', 'dog')

(lofi   <- choice_to_lofi(choice, options))
#> [1] 0 0 3

lofi_to_choice(lofi  , options)
#> [1] "apple" "apple" "dog"