Tuesday, December 24, 2024

MySQL BIN() Function

 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:

  1. Convert a number to binary:

    SELECT BIN(5) AS BinaryValue; -- Output: '101'
    
  2. Convert a larger number:

    SELECT BIN(16) AS BinaryValue; -- Output: '10000'
    
  3. Handle NULL input:

    SELECT BIN(NULL) AS BinaryValue; -- Output: NULL
    
  4. Convert a negative number:

    SELECT BIN(-10) AS BinaryValue; -- Output: '1010' (absolute value is used)
    
  5. 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