m0j0
m0j0

Reputation: 3874

Working with hex numbers in MySQL

I have a stored procedure that needs to convert hexadecimal numbers to their decimal equivalent. I've read the documentation for the UNHEX() function, but it is returning a binary value. What I'm wanting to do is something like this:

CREATE PROCEDURE foo( hex_val VARCHAR(10) )
BEGIN
    DECLARE dec_val INTEGER;

    SET dec_val = UNHEX( hex_val );

    -- Do something with the decimal value
    select dec_val;
END

What am I missing? How can I convert the UNHEX()'d value to a unsigned integer?

Upvotes: 11

Views: 19733

Answers (3)

Phunny
Phunny

Reputation: 71

cast(conv(hex_val, 16, 10) as unsigned integer) that should be solve the problem....

Upvotes: 7

Greg
Greg

Reputation: 321864

You can use the CONV() function to convert between bases.

SET dec_val = CONV(hex_val, 16, 10);

Upvotes: 23

Robert Gamble
Robert Gamble

Reputation: 109192

conv(hex_val, 16, 10)

Will convert a number of base 16 to base 10. The UNHEX function does something completely different, it converts pairs of hex digits to characters.

Upvotes: 8

Related Questions