The BIN() function in MySQL is used to convert a decimal (base-10) number into its binary (base-2) representation as a string.
Syntax:
BIN(number)
Parameters:
number: A positive integer to be converted into binary.
Returns:
- A binary string representation of the given number.
- If the input is NULL, the function returns NULL.
- If the input is negative, the function converts the absolute value of the number before returning the binary representation.
Examples:
-
Convert a number to binary:
SELECT BIN(5) AS BinaryValue; -- Output: '101' -
Convert a larger number:
SELECT BIN(16) AS BinaryValue; -- Output: '10000' -
Handle NULL input:
SELECT BIN(NULL) AS BinaryValue; -- Output: NULL -
Convert a negative number:
SELECT BIN(-10) AS BinaryValue; -- Output: '1010' (absolute value is used) -
Using BIN() in combination with other functions:
SELECT BIN(POW(2, 3)) AS BinaryValue; -- Output: '1000'
Practical Use:
The BIN() function is useful when dealing with:
- Binary arithmetic.
- Debugging or inspecting binary representations of integers.
- Database fields storing binary or bitmask values.
Would you like to see an example with a table or a more complex query?
No comments:
Post a Comment