用SQLite实现十六进制字符串到无符号整数的转换

rpppsulh  于 2023-03-03  发布在  SQLite
关注(0)|答案(1)|浏览(286)

我有一些字符串字段,它们以相反的字节顺序存储无符号整数的十六进制表示。我想将其转换回整数。
例如,字符串deadbeef必须生成数字4022250974

hyrbngr7

hyrbngr71#

我找到了正常字节顺序here的答案:

WITH RECURSIVE
  unhex(str, val, weight) AS (
    SELECT 'deadbeef', 0, 1
      UNION ALL
        SELECT 
          substr(str, 1, length(str) - 1),
          val + (instr('0123456789abcdef', substr(str, length(str), 1)) - 1) * weight,
          weight * 16
        FROM unhex WHERE length(str) > 0
  )
  SELECT val FROM unhex order by weight desc limit 1;

然后我把它修改成同样的反字节顺序:

WITH RECURSIVE unhex(str, val, weight) AS (
  SELECT 
    'efbeadde', 0, 1
  UNION ALL 
  SELECT 
    substr(str, 3), 
    val + (instr('0123456789abcdef', substr(str, 2, 1)) - 1) * weight + (instr('0123456789abcdef', substr(str, 1, 1)) - 1) * weight * 16, 
    weight * 256 
  FROM unhex WHERE length(str) > 0
)
SELECT val FROM unhex order by weight desc limit 1;

相关问题