MySQL CONV() Function
MySQL CONV() Function
The MySQL CONV() function converts a number from one numeral base (from_base) into another (to_base) and returns the result as a string. It supports any base between 2 and 36, covering binary, octal, decimal, and hexadecimal conversions.
Syntax
CONV(N, from_base, to_base)
N: The integer or string representation of the number to convert.from_base: Source base as an integer from2to36.to_base: Target base as an integer from2to36(or-2to-36for signed output).
MySQL internally computes the conversion using 64-bit integer precision (BIGINT), and uses letters A through Z for digits above 9.
Practical Example
Suppose demo_products stores hardware color codes or device IDs in decimal, and you want hexadecimal and binary representations for an engineering export.
SELECT
product_id,
product_name,
CONV(product_id, 10, 16) AS hex_id,
CONV(product_id, 10, 2) AS binary_id
FROM demo_products
WHERE product_id IN (15, 255, 1024);
| product_id | product_name | hex_id | binary_id |
|---|---|---|---|
| 15 | Smart Sensor | F | 1111 |
| 255 | LED Strip | FF | 11111111 |
| 1024 | Network Switch | 400 | 10000000000 |
Common Mistakes & NULL Behavior
- NULL and out-of-range bases:
CONV()returnsNULLif any argument isNULL, or ifabs(from_base)orabs(to_base)is outside2..36. - Signed vs unsigned negative numbers: If
to_baseis positive (e.g.,16),CONV(-10, 10, 16)formats-10as an unsigned 64-bit value (FFFFFFFFFFFFFFF6). Pass a negativeto_baselikeCONV(-10, 10, -16)to get'-A'. - Leading invalid characters:
CONV('1Z', 16, 10)stops parsing at'Z'(not a valid base-16 digit) and converts only'1', returning'1'instead of an error. - 64-bit overflow: Values exceeding unsigned 64-bit
BIGINT(18446744073709551615) clamp to the maximum 64-bit value rather than raising an error.
Frequently Asked Questions
How do I convert hex to decimal in MySQL?
Call CONV(hex_str, 16, 10). For example, CONV('FF', 16, 10) returns '255'.
Why does CONV(-1, 10, 16) return 16 F characters?
Because a positive to_base formats values as unsigned 64-bit integers. Pass -16 as to_base (CONV(-1, 10, -16)) to preserve the minus sign and return '-1'.
What data type does CONV() return?
CONV() always returns a string (VARCHAR), even when to_base is 10. Cast to UNSIGNED or SIGNED if you need arithmetic sorting.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.