Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite Int to Hex and Hex to Int in query

I have some numeric data that is given to me in INTEGER form. I insert it along with other data into SQLite but when I write it out The INTEGER Numbers need to be 8 digit Hex Numbers with leading zeros.

Ex.

Input

400 
800 
25 
76

Output

00000190 
00000320 
00000019 
0000004C

Originally I was converting them as I read them in and storing them as TEXT like this.

stringstream temp;
temp << right << setw(8) << setfill('0') << hex << uppercase << VALUE;

But life is never easy and now I have to create a second output in INTEGER form not HEX. Is there a way to convert INTEGER numbers to HEX or HEX numbers to INTEGERS in SQLite?

I'd like to avoid using C++ to change data after it is in SQLite because I've written a few convent export functions that take a queries result and print them to a file. If I need to touch the data during the queries return I couldn't use them.

I've looked at the HEX() function in SQLite but that didn't have desired results. Could I make a function or would that be very inefficient? I'm doing this over a really big data set so anything expensive should be avoided.

Note: I'm using SQLites C/C++ interface with Visual Studios 2010.

like image 427
Dan Avatar asked Jan 11 '13 23:01

Dan


People also ask

How can I convert a hex string to an integer value?

To convert a hexadecimal string to a numberUse the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer. The first argument of the ToInt32(String, Int32) method is the string to convert. The second argument describes what base the number is expressed in; hexadecimal is base 16.

What is hex in SQLite?

SQLite hex() function The hex() function interprets its argument as a BLOB and returns a string which is the upper-case hexadecimal rendering of the content of that blob.

What is a hex value in SQL?

HEX() : This function in MySQL is used to return an equivalent hexadecimal string value of a string or numeric Input. If the input is a string then each byte of each character in the string is converted to two hexadecimal digits.


2 Answers

You can use sqlite3 printf() function:

CREATE TABLE T (V integer);
insert into T(V) values(400), (800), (25), (76);
select printf('%08X', V) from T;
like image 82
BigTick Avatar answered Sep 18 '22 23:09

BigTick


You can use sqlite3_create_function. See an example

like image 22
cprogrammer Avatar answered Sep 22 '22 23:09

cprogrammer