I have a bitmap stored as a VARCHAR
in Netteza. Need to convert that VARCHAR
to a binary string in Netezza.
Input (Netezza col value - VARCHAR
) = '0xFFFFFFFFFFFFFFFF'
Desired output (VARCHAR
)->
'1111111111111111111111111111111111111111111111111111111111111111'
Is there a way to do this using Netezza query ?
I tried
SELECT CAST('0xFFFFFFFFFFFFFFFF' AS VARBINARY(64) );
but that throws an error
ERROR [HY000]ERROR: Cannot cast type 'VARCHAR' to 'VARBINARY'
You can convert a hex string into binary data and store it in either a VARCHAR or VARBINARY column. I tend to prefer VARCHAR because of the rather limited CASTs that are available for VARBINARY.
To convert a hex string to binary and stored it in a VARCHAR, use the hextoraw function provided with the SQL Extension Toolkit. This is included with Netezza but must be configured and made available by your administrator.
To convert a hex string to binary and store it in a VARBINARY, use the hex_to_binary function included with Netezza (added in v 7.2).
From there you'll need a UDF to handle the bit calculations that you want to do. I've put together three simple UDFs that I believe will suit your purpose.
FirstBit returns the position of the first non-zero bit. BitCount returns the total count of non-zero bits. CharToBase2 converts a binary values in a VARCHAR of 1s and 0s.
I think the first two get the end result that you need without the third, but in case you still wanted that, it's here.
Here are the sources for each. Please note that I am a terrible C++ coder, and would likely be fired if that were my job, so caveat emptor.
BitCount.cpp
FirstBit.cpp
CharToBase2.cpp
Finally, here are the scripts I used to compile and install each.
install_firstbit.sh DBNAME
install_bitcount.sh DBNAME
install_chartobase2.sh DBNAME
I think you'll need to define a UDF in C, register it with the database, and then call it on your column.
I'd start by looking at either this answer or this one. In both of those cases you'd likely have to strip the leading
0x
.following suggestions from @ScottMcG - constructing a UDF to convert hex string to binary string.
input -> 'F0F' desired output -> '11110000111'
----------HexToBin.cpp------
--------install_hextobin.sh DBNAME-------
Sample results