Monday, 15 February 2010

bash - How to split blob into Byte Array In shell script? -



bash - How to split blob into Byte Array In shell script? -

i have blob in postgresql database. have inserted c construction it.

struct temp { uint64_t a, uint64_t b, uint64_t c };

now when write q query in shell retrieving it.

select resource,.....,blob_column rtable rid is=1

i got result blob database. result

x00911ee3561ac801cb0783462586cf01af00000000000000

but in shell script need iterate on , display result on console. tried different things awe,split , convert_from ,convert function nil helping me.

can tell me how can read hex string , integers?

is kind of exersise in programmer-torture? can't imagine why you'd perchance this. not to the lowest degree because struct-as-a-blob subject padding , alignment vary compiler compiler , platform platform. then, it'll vary between architectures because of endianness differences. @ to the lowest degree used fixed-width types.

assuming care little-endian , compilers don't add together padding or alignment (likely struct that's 3 64-bit fields) it's possible. doesn't create great idea.

my preferred approach utilize python code struct, e.g.

python - "x00911ee3561ac801cb0783462586cf01af00000000000000" <<__end__ import sys import struct print "{} {} {}".format(*struct.unpack('@qqq', sys.argv[1][1:].decode("hex"))) __end__

as can handle endianness , packing using appropriate modifiers, , can consume output in shell script.

if that's not convenient/suitable, it's possible in bash, absolutely horrible. little-endian, unpadded/packed-unaligned:

to decode each value (adapted http://stackoverflow.com/a/3678208/398670):

$ x=00911ee3561ac801 $ echo $(( 16#${x:14:2}${x:12:2}${x:10:2}${x:8:2}${x:6:2}${x:4:2}${x:2:2}${x:0:2} ))

so, total deal:

x=x00911ee3561ac801cb0783462586cf01af00000000000000 uint64_dec() { echo $(( 16#${1:14:2}${1:12:2}${1:10:2}${1:8:2}${1:6:2}${1:4:2}${1:2:2}${1:0:2} )) } uint64_dec ${x:1:16} uint64_dec ${x:17:16} uint64_dec ${x:33:16}

produces:

128381549860000000 130470408871937995 175

now, sense dirty , need go wash. strongly suggest following:

create type my_struct (a numeric, b numeric, c numeric);

then using my_struct instead of bytea field. or utilize 3 numeric columns. can't utilize bigint because pg doesn't have 64-bit unsigned integer.

bash postgresql shell blob psql

No comments:

Post a Comment