In MySQL you can use the BIN() function to return a binary representation of a number. This function actually returns a string representation of the binary value.
Syntax
Here’s how the syntax goes:
BIN(N)
Where
N
is the number you need the binary representation of.Example
Here’s a basic example:
SELECT BIN(3);
Result:
+--------+ | BIN(3) | +--------+ | 11 | +--------+
In this case, the result is
11
. This is because 11 is the binary value of 3 in decimal.
Here’s another example to demonstrate various binary values from numbers ranging between 1 and 10:
SELECT BIN(1) AS '1', BIN(2) AS '2', BIN(3) AS '3', BIN(4) AS '4', BIN(5) AS '5', BIN(6) AS '6', BIN(7) AS '7', BIN(8) AS '8', BIN(9) AS '9', BIN(10) AS '10';
Result:
+------+------+------+------+------+------+------+------+------+------+ | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | +------+------+------+------+------+------+------+------+------+------+ | 1 | 10 | 11 | 100 | 101 | 110 | 111 | 1000 | 1001 | 1010 | +------+------+------+------+------+------+------+------+------+------+
BIN() vs CONV()
The above operations could also be done using the
CONV()
function. This function enables you to convert numbers between different bases (so you’re not just limited to binary).
Here’s an example of using
CONV()
to convert a number to binary:SELECT CONV(3, 10, 2);
Result:
+----------------+ | CONV(3, 10, 2) | +----------------+ | 11 | +----------------+
Here, we convert
3
from base 10 to base 2 (binary).
0 comments:
Post a Comment