From 1ce4368567ae9aa3e7f8ddb7f84b17a6bffa7ef8 Mon Sep 17 00:00:00 2001 From: Florian Deljarry Date: Mon, 12 Aug 2019 16:15:24 -0400 Subject: [PATCH] text/abstract_text: Adds the float conversion in exponential hexadecimal notation Signed-off-by: Florian Deljarry --- lib/core/text/abstract_text.nit | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/lib/core/text/abstract_text.nit b/lib/core/text/abstract_text.nit index 06989ef..0072ec8 100644 --- a/lib/core/text/abstract_text.nit +++ b/lib/core/text/abstract_text.nit @@ -2033,7 +2033,7 @@ redef class Float # # see `to_precision` for a custom precision. redef fun to_s do - var str = to_precision( 3 ) + var str = to_precision(3) if is_inf != 0 or is_nan then return str var len = str.length for i in [0..len-1] do @@ -2072,9 +2072,23 @@ redef class Float end var size = to_precision_size(decimals) - var cstr = new CString(size+1) - to_precision_fill(decimals, size+1, cstr) - return cstr.to_s_unsafe(byte_length=size, copy=false) + var cstr = new CString(size + 1) + to_precision_fill(decimals, size + 1, cstr) + return cstr.to_s_unsafe(byte_length = size, copy = false) + end + + # Returns the hexadecimal (`String`) representation of `self` in exponential notation + # + # ~~~ + # assert 12.345.to_hexa_exponential_notation == "0x1.8b0a3d70a3d71p+3" + # assert 12.345.to_hexa_exponential_notation.to_f == 12.345 + # ~~~ + fun to_hexa_exponential_notation: String + do + var size = to_precision_size_hexa + var cstr = new CString(size + 1) + to_precision_fill_hexa(size + 1, cstr) + return cstr.to_s_unsafe(byte_length = size, copy = false) end # Required string length to hold `self` with `nb` decimals @@ -2088,6 +2102,16 @@ redef class Float private fun to_precision_fill(nb, size: Int, cstr: CString) `{ snprintf(cstr, size, "%.*f", (int)nb, self); `} + + # The lenght of `self` in exponential hexadecimal notation + private fun to_precision_size_hexa: Int`{ + return snprintf(NULL, 0, "%a", self); + `} + + # Fill `cstr` with `self` in exponential hexadecimal notation + private fun to_precision_fill_hexa(size: Int, cstr: CString) `{ + snprintf(cstr, size, "%a", self); + `} end redef class Char -- 1.7.9.5