Unsigned 64 bit integer to numeric

Started by Dmitry Dolgovabout 6 years ago4 messages
#1Dmitry Dolgov
9erthalion6@gmail.com

Hi,

Probably a simple question, but I don't see a simple answer so far. In
one extension I want to convert uint64 into a numeric to put it
eventually into a jsonb object. As far as I see in numeric.c there are
functions only for signed int64. Is there a way to achive this with
uint64 (without duplicating significant part of numeric implementation
in the extension)?

#2didier
did447@gmail.com
In reply to: Dmitry Dolgov (#1)
Re: Unsigned 64 bit integer to numeric

Hi,
I don't think so, but there's an (unmaintained?) uint extension at
https://github.com/petere/pguint.git

On Wed, Dec 4, 2019 at 11:24 AM Dmitry Dolgov <9erthalion6@gmail.com> wrote:

Show quoted text

Hi,

Probably a simple question, but I don't see a simple answer so far. In
one extension I want to convert uint64 into a numeric to put it
eventually into a jsonb object. As far as I see in numeric.c there are
functions only for signed int64. Is there a way to achive this with
uint64 (without duplicating significant part of numeric implementation
in the extension)?

#3Andrew Gierth
andrew@tao11.riddles.org.uk
In reply to: Dmitry Dolgov (#1)
Re: Unsigned 64 bit integer to numeric

"Dmitry" == Dmitry Dolgov <9erthalion6@gmail.com> writes:

Dmitry> Hi,

Dmitry> Probably a simple question, but I don't see a simple answer so
Dmitry> far. In one extension I want to convert uint64 into a numeric
Dmitry> to put it eventually into a jsonb object. As far as I see in
Dmitry> numeric.c there are functions only for signed int64. Is there a
Dmitry> way to achive this with uint64 (without duplicating significant
Dmitry> part of numeric implementation in the extension)?

Sure. Flip the top bit; convert the value as if signed; then subtract
-(2^63) from the result. (Easier to subtract -(2^63) than to add 2^63,
since the former can itself be represented in a signed int64 for easy
conversion to numeric.)

--
Andrew (irc:RhodiumToad)

#4Dmitry Dolgov
9erthalion6@gmail.com
In reply to: Andrew Gierth (#3)
Re: Unsigned 64 bit integer to numeric

On Wed, Dec 04, 2019 at 11:49:20AM +0000, Andrew Gierth wrote:

"Dmitry" == Dmitry Dolgov <9erthalion6@gmail.com> writes:

Dmitry> Hi,

Dmitry> Probably a simple question, but I don't see a simple answer so
Dmitry> far. In one extension I want to convert uint64 into a numeric
Dmitry> to put it eventually into a jsonb object. As far as I see in
Dmitry> numeric.c there are functions only for signed int64. Is there a
Dmitry> way to achive this with uint64 (without duplicating significant
Dmitry> part of numeric implementation in the extension)?

Sure. Flip the top bit; convert the value as if signed; then subtract
-(2^63) from the result. (Easier to subtract -(2^63) than to add 2^63,
since the former can itself be represented in a signed int64 for easy
conversion to numeric.)

Indeed, looks like this does the trick, thank you!