View Source ByteOrderedFloat (ByteOrderedFloat v0.1.1)

ByteOrderedFloat is used to encode and decode float values into big-endian-like, order-preserving binaries.

acknowledgements

Acknowledgements

Big thanks to Aravind Ravi-Sulekha for a super helpful article.

The description:

The most significant bit is the sign bit. As all positive numbers are higher than all negative numbers, we should flip the sign bit so it’s 1 for positive numbers and 0 for negative numbers.

For negative numbers, we additionally perform a bitwise NOT of the E and M bits so that larger negative numbers get sorted before smaller ones.

Source: https://medium.com/@aravindet/order-preserving-encoding-for-floats-cde09c978629

Link to this section Summary

Functions

Decodes an ByteOrderedFloat encoded binary into a float.

Encodes floats into a 8-byte binary that is float-order preserving.

Link to this section Functions

@spec decode(any()) :: :error | {:ok, float()}

Decodes an ByteOrderedFloat encoded binary into a float.

examples

Examples

iex> {:ok, e} = ByteOrderedFloat.encode(-1.0)
iex> ByteOrderedFloat.decode(e)
{:ok, -1.0}

iex> {:ok, e} = ByteOrderedFloat.encode(0.0)
iex> ByteOrderedFloat.decode(e)
{:ok, 0.0}

iex> {:ok, e} = ByteOrderedFloat.encode(1.0)
iex> ByteOrderedFloat.decode(e)
{:ok, 1.0}

iex> ByteOrderedFloat.decode("1.0")
:error
@spec encode(any()) :: :error | {:ok, <<_::64>>}

Encodes floats into a 8-byte binary that is float-order preserving.

examples

Examples

iex> ByteOrderedFloat.encode(-1.0)
{:ok, <<64, 15, 255, 255, 255, 255, 255, 255>>}

iex> ByteOrderedFloat.encode(0.0)
{:ok, <<128, 0, 0, 0, 0, 0, 0, 0>>}

iex> ByteOrderedFloat.encode(1.0)
{:ok, <<191, 240, 0, 0, 0, 0, 0, 0>>}

iex> ByteOrderedFloat.encode(nil)
:error