Re: BUG #6015: to_hex and negative integer

From: Craig Ringer <craig(at)postnewspapers(dot)com(dot)au>
To: Marco Spiga <ctxspi(at)gmail(dot)com>
Cc: pgsql-bugs(at)postgresql(dot)org
Subject: Re: BUG #6015: to_hex and negative integer
Date: 2011-05-09 06:41:58
Message-ID: 4DC78CB6.9080101@postnewspapers.com.au
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

On 09/05/11 02:07, Marco Spiga wrote:
>
> The following bug has been logged online:
>
> Bug reference: 6015
> Logged by: Marco Spiga
> Email address: ctxspi(at)gmail(dot)com
> PostgreSQL version: 8.3.12
> Operating system: Ubuntu Linux on kernel version 2.6.30.5
> Description: to_hex and negative integer
> Details:
>
> Hi!
> First, thank for your excellent software.
> My question is:
> Why when I try: SELECT to_hex(-1)
> it give me a strange result: ffffffff

That's not a bug, it's exactly what I'd expect to happen.

What did you expect to get instead? -0x01 ? 0xffff? 0xffffffffffffffff?

Don't understand why the result is the expected one by most people? Read
this: http://en.wikipedia.org/wiki/Two's_complement

... so you understand how signed numbers are represented internally by
most binary computer systems.

As it happens, the real problem with to_hex() on a negative number is
that the result doesn't make much sense unless you know the size of the
representation. For example, ffff can mean 65535 if interpreted as an
unsigned 16-bit interger, or can mean -1 if interpreted as a signed
16-bit int. ffffffff can mean 4294967295 if interpreted as an unsigned
32 bit int or as a signed 64-bit integer, but is -1 if interpreted as a
signed 32-bit integer.

Essentially, to_hex takes the _size_ of the input datum as an implicit
input. This means that you should NOT USE IT in any context where you do
not know the data type of the input, because its results vary in meaning
depending on what you feed into it.

classads=> select to_hex(-1 :: integer);
to_hex
----------
ffffffff
(1 row)

classads=> select to_hex(-1 :: bigint);
to_hex
------------------
ffffffffffffffff
(1 row)

--
Craig Ringer

In response to

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message Rodriguez Fernando 2011-05-09 11:36:53 column check mistake or not?
Previous Message Marco Spiga 2011-05-08 18:07:41 BUG #6015: to_hex and negative integer