1

issue is this: in (pl)python code, we've calculated an integer = 26663. Can easily convert this to hex using hex(myint) = 0x6827

So far so good!

Now, how to write this value -into a concatenation of strings- into a PostgreSQL (v9) bytea field? The DB is UTF8-encoded, if this matters.

EG, neither of these examples will work:

Here, of course, I cannot concatenate 'str' and 'int' objects:

rv = plpy.execute(plan, [ (string1 + 6827) ])

This one inputs the wrong hex code for 0x6827

rv = plpy.execute(plan, [ (string1 + str('6827')) ])

Help!

0

1 Answer 1

2

I'm not familiar with Postgres, but the hex(n) function returns a string representation of the numeric value of n in hexadecimal. The nicest way in my opinion to concatenate this with a string is to use format strings. For example:

rv = plpy.execute(plan, [ ( 'foo %s bar' % hex(6827) ) ] )

If the string is really in a variable called string1, and you only need to append it with the hex value, then simple concatenation using the + sign will work fine:

rv = plpy.execute(plan, [ ( string1 + hex(6827) ) ])

This works without conversion because the hex() function returns a string.

If you don't actually want to store a printable string representation, but rather a binary string, use the struct module to create an array of bytes.

import struct
bytes = struct.pack('i', 6827) # Ignoring endianness

A lot of people are confused about what storing something as "binary" actually means, and since you are using a field type (bytea) which seems to be intended for binary storage, maybe this is what you actually want?

The returned value from bytes will be a string that you can either concatenate with another string, or continue to pack more binary values into.

See the struct module documentation for more information!

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for your comment - I'll check out the struct module now. Yes, indeed, I think the struct module may be what I need. This is going into a 'string' of 4 bytes.
Yes, it looks like struct.pack will do it, but am having a heck of a time sorting through the formatting options; I'm trying to 'pack left', on a little-endian machine - something like struct.pack('i', 26663) The objective being 4 bytes, I think this kind of output from pack would do the trick: \x00\x00\x68\x27 Can you offer any further guidance?
This seems to have done it! bytes = struct.pack('>l', myinteger) It's a bit counterintuitive, though, as this seems to be syntax for big-endianness - while we're on a little-endian machine...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.