1

I'm using Python's struct.pack function to pack various data types into a common 32-bit integer field in PostgreSQL. The drawback is that I can't operate with these values in the database, I have to perform a struct.unpack in Python on the data to know what it represents.

If I pack a 32-bit float into this field, is there any way to get PostgreSQL to do the conversion for me?

I tried this but it didn't work:

select cast(cast(value as bit(32)) as float4) ...

It will successfully cast the integer to bit(32) but it won't convert that back to a float.

4

2 回答 2

4

An answer you are probably not looking for: Don't do that.

This is a violation of the basics: a value in a database should be atomic, not divisible into other values. All of the database's operations (did I mention all) are tuned to handling individual values. You are "fighting the framework" here.

Even if you can pull it off, it will be a drag on performance. Plus the database is not reportable, it's not just that you are having this issue now, every attempt to read this data for any reason will run into this problem.

Well, I don't want to go into a rant, 'nuf said.

于 2011-02-04T02:49:44.020 回答
1

最简单的解决方案,我确信您考虑过并放弃的一个解决方案是将 32 位浮点值存储在定义为使用 32 位浮点数据类型的列中。

CAST() 对您不起作用,因为 a) CAST() 对 C 结构、字节序或填充字节一无所知,并且 b) 您不能将位数据类型转换为浮点数据类型。(不过,您可以将位数据类型转换为整数。)

于 2011-02-03T21:15:54.557 回答