Re: to_hex() for negative inputs - Mailing list pgsql-hackers

From Aleksander Alekseev
Subject Re: to_hex() for negative inputs
Date
Msg-id CAJ7c6TNfbbcqZbw03oxN7-U0h2oU=kwoqoHJG5LdU8e3r7zdoQ@mail.gmail.com
Whole thread Raw
In response to to_hex() for negative inputs  (Dean Rasheed <dean.a.rasheed@gmail.com>)
Responses Re: to_hex() for negative inputs
List pgsql-hackers
Hi Dean,

> I only recently realised that to_hex() converts its input to unsigned
> before converting it to hex (something that's not mentioned in the
> docs):

Technically the documentation is accurate [1]:

"""
Converts the number to its equivalent hexadecimal representation.
"""

But I agree that adding an example with negative numbers will not
hurt. Would you like to submit a patch?

> I also think it might be useful for it to gain a couple of boolean options:

Adding extra arguments for something the user can implement
(him/her)self doesn't seem to be a great idea. With this approach we
may end up with hundreds of arguments one day.

> 1). An option to output a signed value (defaulting to false, to
> preserve the current two's complement output).

This in particular can be done like this:

```
=# select case when sign(x) > 0 then '' else '-' end || to_hex(abs(x))
from ( values (123), (-123) ) as s(x);
 ?column?
----------
 7b
 -7b
(2 rows)
```

> 2). An option to output the base prefix "0x" (which comes after the
> sign, making it inconvenient for the user to add themselves).

Ditto:

```
=# select '0x' || to_hex(x) from ( values (123), (-123) ) as s(x);
  ?column?
------------
 0x7b
 0xffffff85
```

[1]: https://www.postgresql.org/docs/current/functions-string.html

-- 
Best regards,
Aleksander Alekseev



pgsql-hackers by date:

Previous
From: Melanie Plageman
Date:
Subject: Re: Monotonic WindowFunc support for ntile(), percent_rank() and cume_dist()
Next
From: Robert Haas
Date:
Subject: Re: Non-superuser subscription owners