Collections:
BIN() - Converting Integer to Binary String
How to convert an integer to a binary string using the BIN() function?
✍: FYIcenter.com
BIN(int) is a MySQL built-in function that
converts an integer to binary string.
For example:
SELECT BIN(1), BIN(2), BIN(4), BIN(8), BIN(16), BIN(1024); -- +--------+--------+--------+--------+---------+-------------+ -- | BIN(1) | BIN(2) | BIN(4) | BIN(8) | BIN(16) | BIN(1024) | -- +--------+--------+--------+--------+---------+-------------+ -- | 1 | 10 | 100 | 1000 | 10000 | 10000000000 | -- +--------+--------+--------+--------+---------+-------------+ SELECT BIN(x'ff'), BIN(x'ffff'), BIN(x'ffffffff'); -- +------------+------------------+----------------------------------+ -- | BIN(x'ff') | BIN(x'ffff') | BIN(x'ffffffff') | -- +------------+------------------+----------------------------------+ -- | 11111111 | 1111111111111111 | 11111111111111111111111111111111 | -- +------------+------------------+----------------------------------+
If the input is not an integer, BIN() will try to cast it to an integer first. For example:
SELECT BIN(3.14), BIN(8.8), BIN('8.8'), BIN('1024 Bytes');
-- +-----------+----------+------------+-------------------+
-- | BIN(3.14) | BIN(8.8) | BIN('8.8') | BIN('1024 Bytes') |
-- +-----------+----------+------------+-------------------+
-- | 11 | 1000 | 1000 | 10000000000 |
-- +-----------+----------+------------+-------------------+
SELECT BIN(TRUE), BIN(FALSE), BIN(NULL);
-- +-----------+------------+-----------+
-- | BIN(TRUE) | BIN(FALSE) | BIN(NULL) |
-- +-----------+------------+-----------+
-- | 1 | 0 | NULL |
-- +-----------+------------+-----------+
If you want to convert an integer from a binary string to decimal string, you need to use the CONV(str, 2, 10) function. For example:
SELECT BIN(1024), CONV('10000000000', 2, 10);
-- +-------------+----------------------------+
-- | BIN(1024) | CONV('10000000000', 2, 10) |
-- +-------------+----------------------------+
-- | 10000000000 | 1024 |
-- +-------------+----------------------------+
Reference information of the BIN() function:
BIN(int): str Returns the binary representation of a given integer. Arguments, return value and availability: int: Required. The integer to be converted. str: Return value. The converted binary string. Available since MySQL 4.0.
Related MySQL functions:
⇒ BIT_COUNT() - Counting '1' in Binary String
⇐ ATAN2() - 2-Argument Arctangent
2024-11-23, 1160🔥, 0💬
Popular Posts:
How To End a Stored Procedure Properly in SQL Server Transact-SQL? Where the end of the "CREATE PROC...
How To Convert Binary Strings into Integers in SQL Server Transact-SQL? Binary strings and integers ...
What Privilege Is Needed for a User to Delete Rows from Tables in Another Schema in Oracle? For a us...
How To Connect the Oracle Server as SYSDBA in Oracle? This is Step 4. The best way to connect to the...
Where to find answers to frequently asked questions on CREATE, ALTER and DROP Statements in MySQL? H...