The CONV() function in MySQL is used to convert a number from one numeric base system to another. The result is returned as a string value. It allows conversion between bases ranging from 2 to 36 (or -2 to -36 for negative bases).
Syntax
CONV(number, from_base, to_base)
Parameters
- number: The numeric value that you want to convert.
- from_base: The base system of the input number. This must be a value between 2 and 36.
- to_base: The base system to convert the number to. This can also be a value between 2 and 36, or between -2 and -36.
Definition and Usage
- The
CONV()function converts a number from one numeric base system (such as binary, decimal, or hexadecimal) to another. - The result is returned as a string, and any invalid parameters (like bases outside the acceptable range) will cause the function to return
NULL.
Technical Details
- Works in: From MySQL 4.0
- Return Type: A string representing the number in the new base system.
- Return Values: If any of the parameters are invalid or
NULL, the function returnsNULL.
Example Usage
Example 1: Convert a Number from Decimal to Binary
Convert the decimal number 15 to binary:
SELECT CONV(15, 10, 2);
This will return 1111 as the binary representation of 15.
Example 2: Convert a Number from Decimal to Hexadecimal
Convert the decimal number 255 to hexadecimal:
SELECT CONV(255, 10, 16);
This will return FF as the hexadecimal representation of 255.
Example 3: Convert from Hexadecimal to Decimal
Convert the hexadecimal number A to decimal:
SELECT CONV('A', 16, 10);
This will return 10 as the decimal representation of A.
Example 4: Convert from Base 36 to Decimal
Convert the number Z from base 36 to decimal:
SELECT CONV('Z', 36, 10);
This will return 35 as the decimal representation of Z.
Use Cases
- Base Conversion: Ideal for converting numbers between different numeric systems (binary, octal, decimal, hexadecimal, etc.).
- Handling Custom Encodings: Useful for applications where you need to convert between different numeric bases for encoding or computation.