Skip to content

Commit

Permalink
handle signed integers
Browse files Browse the repository at this point in the history
  • Loading branch information
thesayyn committed May 8, 2023
1 parent a4dd8f1 commit 7901194
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
10 changes: 7 additions & 3 deletions lib/private/string.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -567,8 +567,10 @@ def hex(number):
Returns:
hexdecimal representation of the number argument
"""
r = number

hex_string = ""
is_signed = number < 0
r = number * -1 if is_signed else number
for _ in range(1000000):
if r > 0:
rem = r % 16
Expand All @@ -577,6 +579,8 @@ def hex(number):
else:
break

hex_string = hex_string if hex_string else "0"
return "{}0x{}".format("-" if number < 0 else "", hex_string)
if not hex_string:
hex_string = "0"

return "{}0x{}".format("-" if is_signed else "", hex_string)

6 changes: 5 additions & 1 deletion lib/tests/string_tests.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,12 @@ def _hex_test_impl(ctx):
asserts.equals(env, hex(1111), "0x457")
asserts.equals(env, hex(97), "0x61")
asserts.equals(env, hex(1000000000000), "0xe8d4a51000")
asserts.equals(env, hex(0), "0x0")
asserts.equals(env, hex(1), "0x1")
# https://en.wikipedia.org/wiki/Signed_zero
asserts.equals(env, hex(0), "0x0")
asserts.equals(env, hex(-0), "0x0")
asserts.equals(env, hex(-1234), "-0x4d2")
asserts.equals(env, hex(-99999999), "-0x5f5e0ff")

return unittest.end(env)

Expand Down

0 comments on commit 7901194

Please sign in to comment.