sqlitetype-conversionblob

SQLite how to convert BLOB byte to INT with built-in functions?


i have an sqlite database that contains a column with BLOB data.
these BLOB data are 4 byte width. i want to split the 4 bytes appart and convert each part to an integer value to calculate with it.
i found out, that i can use SUBSTR(val, start, length) to take the BLOB value appart. the result is still of type BLOB.
but how can i convert the BLOB/byte to an integer value?
is there a built-in function that can convert byte BLOB values to an integer?
or is there a way to convert a hex-string-value into an integer value, so i could play with HEX(val) or QUOTE(val)

CREATE TEMP TABLE IF NOT EXISTS test AS SELECT x'cafe1a7e' AS val;
SELECT (val)
    , TYPEOF(val)
    , HEX(val)
    , QUOTE(val)
    , TYPEOF(HEX(val))
    , TYPEOF(QUOTE(val))
    , CAST(val AS INT)
    , CAST(HEX(val) AS INT)
    , CAST(QUOTE(val) AS INT)
    , SUBSTR(val, 1, 1)
    , TYPEOF(SUBSTR(val, 1, 1))
    , HEX(SUBSTR(val, 1, 1))
    , HEX(SUBSTR(val, 2, 1))
    , HEX(SUBSTR(val, 3, 2))
    , val + val
    , SUBSTR(val, 1, 1) + 1
    , CAST(SUBSTR(val, 1, 1) AS INT)
    FROM test;
DROP TABLE test;

Solution

  • You can convert one hex digit at a time using instr:

    SELECT hex(b), n, printf("%04X", n)
      FROM (SELECT b,
            (instr("123456789ABCDEF", substr(hex(b), -1, 1)) << 0) |
            (instr("123456789ABCDEF", substr(hex(b), -2, 1)) << 4) |
            (instr("123456789ABCDEF", substr(hex(b), -3, 1)) << 8) |
            (instr("123456789ABCDEF", substr(hex(b), -4, 1)) << 12) |
            (instr("123456789ABCDEF", substr(hex(b), -5, 1)) << 16) |
            (instr("123456789ABCDEF", substr(hex(b), -6, 1)) << 20) |
            (instr("123456789ABCDEF", substr(hex(b), -7, 1)) << 24) |
            (instr("123456789ABCDEF", substr(hex(b), -8, 1)) << 28) AS n
        FROM (SELECT randomblob(4) AS b))
    

    Example output:

    D91F8E91|3642723985|D91F8E91
    

    (Simplification of idea from [1].)