summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorHans Raaf <hara@oderwat.de>2015-02-18 18:42:45 +0100
committerHans Raaf <hara@oderwat.de>2015-02-18 18:58:20 +0100
commit88f3b1d99f6601b0ada29d77dfb771d6c9885163 (patch)
treee025e408629a66b54d2229cab0e368c9e2b3ad05
parentb7f11b8b0ad9fb7bb71b71a17d3372e3269e5599 (diff)
downloadNim-88f3b1d99f6601b0ada29d77dfb771d6c9885163.tar.gz
Fixing toHex() to not wrap for long lens.
If you specify a len like 32 toHex() will repeat the given value in the
output. Besides that I believe my implementation is easier and seems not
to change how negative numbers are handled. I also handle the case of
wrapping negative number beyond BiggestInt to "do it right".
-rw-r--r--lib/pure/strutils.nim8
1 files changed, 5 insertions, 3 deletions
diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim
index 17e0b9e63..39f468ee3 100644
--- a/lib/pure/strutils.nim
+++ b/lib/pure/strutils.nim
@@ -395,11 +395,13 @@ proc toHex*(x: BiggestInt, len: int): string {.noSideEffect,
   const
     HexChars = "0123456789ABCDEF"
   var
-    shift: BiggestInt
+    n = x
   result = newString(len)
   for j in countdown(len-1, 0):
-    result[j] = HexChars[toU32(x shr shift) and 0xF'i32]
-    shift = shift + 4
+    result[j] = HexChars[n and 0xF]
+    n = n shr 4
+    # handle negative overflow
+    if n == 0 and x < 0: n = -1
 
 proc intToStr*(x: int, minchars: int = 1): string {.noSideEffect,
   rtl, extern: "nsuIntToStr".} =